[英]How to dynamically create a new div using v-for in Vue.js?
我想根據數組中存在的元素數量動態創建 div。 div 包含由 ProgressBar.js 創建的 html 元素。
這是 Vue.js 代碼
import ProgressBar from 'progressbar.js' var bar; export default { data() { return { fitness: ['Run', 'Cycle'], val: 0.65 } }, mounted(){ this.showProgressBar(this.val); }, created: function() { }, methods:{ showProgressBar: function(val){ new ProgressBar.Circle('#container',{ trailColor: 'gainsboro', trailWidth: 20, color: 'teal', strokeWidth: 20 }).animate(val); } } }
<div class="content" v-for="fitness in fitness"> <span>{{ fitness }}</span> <div id="container"></div> </div>
由於 id 僅與一個 div 相關聯,因此我無法執行會創建另一個 div 的新 ProgressBar.Circle 對象。 每次執行新的 ProgressBar.circle 時,有沒有辦法在 v-for 中動態創建一個具有不同 id 的新 div? 有人可以幫我嗎?
這是一個包裝progressbar.js
的可重用組件。
<template>
<div class="container"><div ref="bar"></div></div>
</template>
<script>
import ProgressBar from "progressbar.js"
export default {
props:["options", "val"],
mounted(){
new ProgressBar.Circle(this.$refs.bar, this.options).animate(this.val)
}
}
</script>
<style>
.container{
width:100px;
height: 100px
}
</style>
以下是它在模板中的使用方式:
<div v-for="fit in fitness" class="fitness">
<div>{{fit.name}}</div>
<progress-bar :val="fit.val" :options="options"></progress-bar>
</div>
工作示例。
一種解決方案是為每個容器 div 提供唯一的 id,並為每個容器創建進度條。
試試下面的代碼 -
import ProgressBar from 'progressbar.js' var bar; export default { data() { return { fitness: ['Dietary Intake', 'Exercise'], val: [0.65, 9] } }, mounted() { this.showProgressBar(); }, created: function() { }, methods: { showProgressBar: function() { this.fitness.forEach((f, i) => { new ProgressBar.Circle('#container-' + i, { trailColor: 'gainsboro', trailWidth: 20, color: 'teal', strokeWidth: 20 }).animate(this.val[i]); }); } } }
<div class="content" v-for="(f, index) in fitness"> <span>{{ f }}</span> <div v-bind:id="`container-${index}`"></div> </div>
更新- val 可以是一個數組。 並且可以從showProgressBar
函數中引用它的值。
我假設fitness
和val
數組的長度是相同的。
更新 2 - 解釋。
所以基本上這里有兩個主要問題需要解決。
container
div 我們需要生成多個container
div,因為會有多個ProgressBars
。 但是我們需要區分它們,所以我們為它們中的每一個創建一個唯一的 id。 這就是以下代碼的作用。
<div class="content" v-for="(f, index) in fitness">
<span>{{ f }}</span>
<div v-bind:id="`container-${index}`"></div>
</div>
因為索引號是唯一的。 將它們添加到“容器”會生成唯一 ID。 請參閱列表渲染
ProgressBars
。 這更簡單,我們只需為每個“適合度”值創建新的ProgressBar
。
this.fitness.forEach((f, i) => {
new ProgressBar.Circle('#container-' + i, {
trailColor: 'gainsboro',
trailWidth: 20,
color: 'teal',
strokeWidth: 20
}).animate(this.val[i]);
參考 - 數組 forEach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.