v-for指令無法讀取nStars道具來執行回圈。我試圖通過使用組件<display-star>來顯示多個星星。但由于某些原因,該組件沒有收到nStars道具來執行回圈。這是我的代碼:
HTML
<h1><display-stars : nStars="3"></display-star> </h1>
邏輯
constapp = Vue. createApp({}); //它包含更多的邏輯,但這并不相關。。
app.component("star"/span>, { template: `<i class="fas fa-star"></i>` })。)
app.component(" empty-star", { template: `<i class="far fa-star"></i>` })。)
app.component("display-star"/span>, {
props: ["nStars"]。
template: `<div class="star-container">
<star v-for="i in nStars" :key="i"></star> <empty-star v-for="j in (5-nStars)" :key="j"> </empty-star>
</div>`。
});
const componentInstance_vm = app.mount("#app"/span>)。
我試著閱讀了關于如何傳遞道具的vue檔案,以及如何使用整數而不是集合的v-for。我可能忘了一些東西,因為我對Vue 3真的很陌生,但我的背景是react。
uj5u.com熱心網友回復:
你是否嘗試過使用索引:
<star v-for="(i, index) in nStars" :key="index"> < /star>
uj5u.com熱心網友回復:
nStars是一個Number。你可以使用v-for 只用陣列或物件。
要創建一個包含3個元素的Array,你可以使用Array.from :
let arr = Array. from({length: 3}) 。
這將創建[undefined, undefined, undefined]。
(你也可以用非未定義的元素創建陣列。參考MDN。)
所以要在Vue中回圈nStars次,請做:
<star v-for=" (o,i) in Array. from({length: nStars})" :key="i"> </star>
其中i是索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310006.html
標籤:
