我想使用 alpine.js 在本地存盤中存盤一個整數值
有一個按鈕可以在按下時將值增加 1。
這是我認為應該是這樣的:
<div id="greeting" class="inner" x-data="{ $store.integer: 0 }">
<button class="button bouncy" @click="$store.integer =1" x-text="$store.integer ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () =>
Alpine.store('store', integer)
})
</script>
這沒有用。我嘗試了其他一些實作,但它們似乎都不起作用。我也嘗試不添加 $store,因為當我這樣做時它顯示整數為“未定義”。
uj5u.com熱心網友回復:
Alpine 有persist 插件,看起來它可能適合您的需求。
https://alpinejs.dev/plugins/persist
<div x-data="{ count: $persist(0) }">
<button x-on:click="count ">Increment</button>
<span x-text="count"></span>
</div>
uj5u.com熱心網友回復:
您在示例代碼中有幾個錯誤。修正后的版本如下:
<div id="greeting" class="inner" x-data="{}">
<button class="button bouncy" @click="$store.integer = 1" x-text="$store.integer ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('integer', 0)
})
</script>
- 在 store 中創建新變數時,第一個引數是變數的名稱,第二個引數是它的初始值。
- 在組件中,您不必在
x-data屬性中重新創建變數,因為它是在alpine:init鉤子中定義的。所以你可以只使用一個空的x-data(假設你在組件中沒有其他變數)。 - 你有一個失蹤
{后=>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414870.html
標籤:
