为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以在 alpineJS 中引用外部 js 文件的代码?

是否可以在 alpineJS 中引用外部 js 文件的代码?

慕斯王 2023-06-15 10:23:40
x-data我有一个 Alpine JS 模板,我想从数组中引用它。我目前在我的 HTML 文件底部的一个<script>标记中声明了它,我想将它移动到一个外部文件中。如果我创建文件并将其与<script src='path/to/file.js'>我的组件链接,则会停止工作。有效的例子:<div x-data="{items}">  <template x-for="(item, index) in items" :key="index">    <a :href="item.link" x-text="item.text"></a>  </template></div><script>  const items = [    { link: 'foo.com', text: 'foo' },    { link: 'bar.com', text: 'bar' },  ]</script>不起作用的示例,其中external.js具有相同的变量赋值<div x-data="{items}">  <template x-for="(item, index) in items" :key="index">    <a :href="item.link" x-text="item.text"></a>  </template></div><script src="external.js"></script>以及 external.js 文件的内容:import 'alpinejs'window.onload = () => {console.log('loaded') // This logs in the console  var items = [    { link: 'foo.com', text: 'foo' },    { link: 'bar.com', text: 'bar' },  ]}我不确定我做错了什么,帮助:(
查看完整描述

1 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

好的,所以你的问题是你items在监听事件的回调中创建变量window.onload。AlpineJs 将在事件触发和定义变量之前已经加载并尝试解析 DOM,包括您的变量。


我们可以通过在 Alpine 组件的属性中console.log添加一个来查看加载顺序:x-init


<div x-data="{}" x-init="console.log('init')"></div>

<script>

window.onload = () => {

    console.log('loaded')

}

</script>

有了这个,这就是我们在开发工具中得到的(工作示例https://jsfiddle.net/hfm7p2a6/):

//img4.sycdn.imooc.com/648a76460001cab404160051.jpg

解决方案

解决这个问题有点取决于你需要做什么items。如果没有加载动态内容(即您不需要执行 ajax 调用来获取数组的内容),那么只需忘记并将onload变量放在脚本文件的顶层(工作示例https:// jsfiddle.net/nms7v4xh/):

// external.js

var items = ['your', 'items', 'array'];

// No window.onload needed

如果您确实需要那里有动态内容,则需要将其注入 AlpineJs 实例。在这里执行此操作的最佳方法可能是通过自定义事件(工作示例https://jsfiddle.net/6dLwqn4g/1/):


<div id="app" x-data="{items: null}" @my-event.window="items = $event.detail.items"></div>


<script>

// Create and dispatch the event

let event = new CustomEvent('my-event', {

    detail: {

        items: ['your', 'dynamic', 'items', 'content']

    }

});

window.dispatchEvent(event);

</script>

@my-event.window在这里,我们使用 AlpineJs 来使用属性(您也可以使用)来侦听窗口上的事件x-on:my-event.window。然后我们可以通过$event.detail属性获得项目数据。

查看完整回答
反对 回复 2023-06-15
  • 1 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信