【问题标题】:Alpine.js: How do I access x-data from a function in an external file?Alpine.js:如何从外部文件中的函数访问 x 数据?
【发布时间】:2021-07-11 21:41:39
【问题描述】:

我刚开始使用 Alpine.js,我了解基础知识,但在将函数移至内联脚本标签之外时无法应用它们。

例如在index.html:

<div x-data="{ loading: false }"/>
  <button
    onClick="post()"
    :class="{ 'active': loading === true }"
  >
    Post Comment
  </button>
</div>

如果post()main.ts 中:

const postComment = () => {
  this.loading = true;
};

window.postComment = postComment;

如何使this 不被定义?

我发现了很多将函数保存在 index.html 中的示例,但没有一个示例将它们保存在单独的文件中。

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    您需要将该方法添加到 AlpineJs 实例以访问相同的范围。但是您可以使用扩展 ... 运算符通过一些对象解构来做到这一点:

    在页面中:

    <div x-data="{
      isLoading: false,
      ...utils
    }">
        // Your content
    </div>
    

    然后在你的外部脚本文件中:

    const utils = {
      post(){
        this.isLoading = true
      }
    }
    
    window.utils = utils
    

    这样做的好处是您可以将加载指示器所需的所有内容放入此外部对象中,以便在需要的任何地方用作 mixin。

    这是一个工作示例:https://codepen.io/stephenoldham/pen/BapvyYr

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多