Search code examples
canvasvue.jsv-for

how to v-for drive canvas tag and save things in the canvas


there is source code https://codesandbox.io/s/9lqnroooxr

How to v-for drive accurately canvas tag?

Is there such a class or a directive?


Solution

  • slice() doesn't modify the original array, and perhaps in the last line you meant splice().

    This creates as many different canvas elements as items in arr:

    NOTE: to have vue.js keep track of which element is which inside the v-for, it's necessary to specify a unique and stable value as the key. Uniqueness alone is not sufficient, it must keep the same value associated to the same element, otherwise vue will get confused!

    In your case the index changes when you remove an entry, while the item is the value that identifies an element. So you have to specify :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>