【问题标题】:Alpine Expression Error: createFormComponent is not defined高山表达式错误:未定义 createFormComponent
【发布时间】:2021-12-09 16:03:39
【问题描述】:

我在 .NET Core 6 MVC 项目中使用 Alpine JS。我已经从https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js 加载了 alpine js 文件。然后我在 Home/Index.cshtml 文件中添加了以下代码。

<form id="myForm"
  x-data="createFormComponent()" 
  x-on:submit.prevent="onSubmit">

  <input id="email" type="text" name="email" 
    x-model="email" />

  <span class="error" style="display: none"
    x-show="error"
    x-text="error"
  ></span>

  <button type="submit">Submit</button>
</form>

@section Scripts {

   <script>
  (function () {
    'use strict';

    window.createFormComponent = function () {
      return {
        email: '',
        error: '',

        onSubmit($event) {
          this.error = !this.email 
            ? 'You must enter an email address' 
            : '';
        },
      };
    };
  })();
</script>

}

但是当我在浏览器中访问页面时,它总是抛出错误“Alpine Expression Error: createFormComponent is not defined”。我试图将它放入一个 js 文件并加载它。还尝试在 alpine:init 事件中定义组件。他们都没有工作。相同的代码适用于从 IIS 提供的纯 html 文件。我不确定这里有什么问题。谁能帮忙。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc alpine.js


    【解决方案1】:

    请务必在您的_Layout.cshtml 或当前页面@section Scripts {...} 中添加js,如下所示:

    <script src="https://unpkg.com/alpinejs" defer></script>
    

    注意:必须添加 HTML defer 属性。

    【讨论】:

    • 它在示例应用程序中运行良好。检查主应用程序。我确实添加了延迟,但我在 src 标记之前添加了它,并且移动到末尾似乎有所作为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2014-05-24
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多