简体   繁体   English

Alpine.js:如何从外部文件中的 function 访问 x 数据?

[英]Alpine.js: How do I access x-data from a function in an external file?

I'm just starting out with Alpine.js, I understand the basics but I'm having trouble applying them when moving functions outside of inline script tags.我刚开始使用 Alpine.js,我了解基础知识,但是在将函数移到内联脚本标签之外时,我无法应用它们。

For example, in index.html :例如,在index.html中:

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

if post() was in main.ts :如果post()main.ts中:

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

window.postComment = postComment;

How do I make it so that this isn't undefined?我怎样才能使它不是未定义this

I've found plenty of examples where functions are kept within index.html , but none where they're in a separate file.我发现了很多将函数保存在index.html中的示例,但没有一个示例将它们保存在单独的文件中。

You'll need to add the method to the AlpineJs instance to access the same scope.您需要将该方法添加到 AlpineJs 实例以访问相同的 scope。 But you can do this with some object destructuring using the spread ... operator:但是您可以通过使用 spread ...运算符进行一些 object 解构来做到这一点:

In the page:在页面中:

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

Then in your external script file:然后在您的外部脚本文件中:

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

window.utils = utils

The nice thing about this is you could put everything you need for a loading indicator in this external object to use as a mixin wherever you need it.这样做的好处是您可以将加载指示器所需的所有内容放入这个外部 object 中,以便在需要的任何地方用作 mixin。

Here's a working example: https://codepen.io/stephenoldham/pen/BapvyYr这是一个工作示例: https://codepen.io/stephenoldham/pen/BapvyYr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM