【问题标题】:Alpine.js Cant bind x-data to functin in external js fileAlpine.js 无法将 x-data 绑定到外部 js 文件中的函数
【发布时间】:2021-02-02 01:20:22
【问题描述】:

我正在使用 alpine.js 创建一个应用程序

这是我的index.html 文件的上下文

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Alpine</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app" x-data="app()">
      <div>
        <button x-on:click="open">Open</button>

        <div x-show="isOpen()" x-on:click.away="close">
          // Dropdown
        </div>
      </div>
    </div>

    <script src="src/index.js"></script>
    <script>
      function app() {
        return {
          show: false,
          open() {
            this.show = true;
          },
          close() {
            this.show = false;
          },
          isOpen() {
            return this.show === true;
          }
        };
      }
    </script>
  </body>
</html>

此代码运行良好,但是,如果我将 app 函数移动到 index.js,我会在控制台中收到错误消息。

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Alpine</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app" x-data="app()">
      <div>
        <button x-on:click="open">Open</button>

        <div x-show="isOpen()" x-on:click.away="close">
          // Dropdown
        </div>
      </div>
    </div>
    <script src="src/index.js"></script>
  </body>
</html>

和 index.js

import "./styles.css";
import "alpinejs";

function app() {
  return {
    show: false,
    open() {
      this.show = true;
    },
    close() {
      this.show = false;
    },
    isOpen() {
      return this.show === true;
    }
  };
}

当我运行此代码时,我收到以下错误:

alpine.js:1907 Uncaught TypeError: app is not a function 在 eval 处(在 tryCatch.el.el (alpine.js:NaN) 处进行评估,:3:54)

CodeSandbox 链接是here

【问题讨论】:

    标签: javascript html parcel alpine.js


    【解决方案1】:

    默认情况下,alpine 将在窗口级别中查找组件。所以这个问题可以通过在窗口中创建一个app 变量来解决,这与你的函数完全相同。

    import "./styles.css";
    import "alpinejs";
    
    window.app = function () {
      return {
        show: false,
        open() {
          this.show = true;
        },
        close() {
          this.show = false;
        },
        isOpen() {
          return this.show === true;
        }
      };
    };
    
    

    Laracasts有一个关于提取alpine js组件的免费视频教程,你可以查看here

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2021-11-08
      • 1970-01-01
      相关资源
      最近更新 更多