繁体   English   中英

如何在 Vue.js 中使用 v-for 动态创建一个新的 div?

[英]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函数中引用它的值。

我假设fitnessval数组的长度是相同的。

更新 2 - 解释。

所以基本上这里有两个主要问题需要解决。

1.生成多个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。 请参阅列表渲染

2. 组件挂载时生成多个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM