第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

慕斯王 2023-06-15 10:23:40
x-data我有一個(gè) Alpine JS 模板,我想從數(shù)組中引用它。我目前在我的 HTML 文件底部的一個(gè)<script>標(biāo)記中聲明了它,我想將它移動(dòng)到一個(gè)外部文件中。如果我創(chuàng)建文件并將其與<script src='path/to/file.js'>我的組件鏈接,則會(huì)停止工作。有效的例子:<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 文件的內(nèi)容:import 'alpinejs'window.onload = () => {console.log('loaded') // This logs in the console  var items = [    { link: 'foo.com', text: 'foo' },    { link: 'bar.com', text: 'bar' },  ]}我不確定我做錯(cuò)了什么,幫助:(
查看完整描述

1 回答

?
慕的地8271018

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊

好的,所以你的問題是你items在監(jiān)聽事件的回調(diào)中創(chuàng)建變量window.onload。AlpineJs 將在事件觸發(fā)和定義變量之前已經(jīng)加載并嘗試解析 DOM,包括您的變量。


我們可以通過在 Alpine 組件的屬性中console.log添加一個(gè)來查看加載順序:x-init


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

<script>

window.onload = () => {

? ? console.log('loaded')

}

</script>

有了這個(gè),這就是我們?cè)陂_發(fā)工具中得到的(工作示例https://jsfiddle.net/hfm7p2a6/):

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

解決方案

解決這個(gè)問題有點(diǎn)取決于你需要做什么items。如果沒有加載動(dòng)態(tài)內(nèi)容(即您不需要執(zhí)行 ajax 調(diào)用來獲取數(shù)組的內(nèi)容),那么只需忘記并將onload變量放在腳本文件的頂層(工作示例https:// jsfiddle.net/nms7v4xh/):

// external.js

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

// No window.onload needed

如果您確實(shí)需要那里有動(dòng)態(tài)內(nèi)容,則需要將其注入 AlpineJs 實(shí)例。在這里執(zhí)行此操作的最佳方法可能是通過自定義事件(工作示例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屬性獲得項(xiàng)目數(shù)據(jù)。

查看完整回答
反對(duì) 回復(fù) 2023-06-15
  • 1 回答
  • 0 關(guān)注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)