-1

有源代码 https://codesandbox.io/s/9lqnroooxr

如何 v-for 准确驱动画布标签?

有这样的类或指令吗?

4

1 回答 1

1

slice()不修改原始数组,也许在最后一行你的意思是splice().

这将创建与以下项目一样多的不同画布元素arr

注意要让vue.js跟踪. v-for_ 仅有唯一性是不够的,它必须保持与相同元素关联的相同值,否则 vue 会混淆!key

在您的情况下,删除条目时索引会更改,而item是标识元素的值。所以你必须指定:key="item".

var app = new Vue({
  el: '#app',
  data () {
    return {
      arr: [],
    };
  },
  created: function () {
		let arr = [];
		arr.push({id:1});//have one canvas and draw things in the canvas
		arr.push({id:2});//have new canvas and also draw things in the canvas
		arr = arr.slice(0,1);//delete first element, the related canvas and other canvas are disordered
		arr.splice(0,0,{id:3});//canvas tags show same disordered
		console.log(arr);
		this.arr = arr;
  }
})
canvas {
  width: 300px;
  height: 150px;
  border: 1px solid green;
  margin: 10px;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <canvas v-for="(item,index) in arr" :key="item"></canvas>
</div>

于 2018-05-01T12:02:25.597 回答