亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否可以在 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/):

http://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 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號