Search code examples
vue.jsremovechildv-for

Vuejs v-for remove element


I have code like :

<div id="files">
  <div v-for="(file, key) in data.files" v-bind:id="key">
    @{{ file }}
    <span v-on:click="removeFile(key)">
      <button>X</button>
    </span>
    <button v-on:click="addFiles()">Add Files</button>
  </div>
</div>

File js

methods: {
   removeFile(key) {
       var elem = document.getElementById("#" + key);
       elem.parentNode.removeChild(elem);
       return false;
   }

When i clicked button, selected file had been deleted as well but it also returned error like:

Uncaught TypeError: Cannot read property 'parentNode' of null

I tried this way but same problem: file had been removed, with error

var parent = document.getElementById("files");
var child = document.getElementById("#" + key);

parent.removeChild(child);

Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

Any idea? Thanks so much!


Solution

  • Replace the content of your removeFile() method with this: (given that the files variable is an array)

    methods: {
       removeFile(key) {
           this.files.splice(key, 1);
       }
    

    You can also use the Vue helper for removing items in an array or a property in an object:

    methods: {
       removeFile(key) {
           this.$delete(this.files, key);
       }