[Vuejs]-Vue – Detect if element been added to v-for object

0👍

You can add a watcher, which gives you the previous values and new values by default. Then you can compare the old values length and new values length to see if an item has been added for example, but of course you can also do other comparison there.

Here’s a modification to your code with a watcher:

var TBL=new Vue({
    el:$(`<table>
        <thead>
            <tr id="tit"><td :colspan="cols.length" v-if="tit!==''">{{ tit }}</td></tr>
            <tr id="cols"><th v-for="ch of cols">{{ ch.txt }}</th></tr>
        </thead>
        <tbody>
            <tr v-for="row of tbl">
                <td v-for="col in row" :colspan="col.cs">{{ col.txt }}</td>
            </tr>
        </tbody>
    </table>`).appendTo(document.body),
    data:{ tit:"",cols:[],tbl:[] },
    methods:{
        // The methods to perform adding/removing of column(s) from the table.
    },
      watch: {
    // whenever cols changes, this function will run
    cols: function (newValue, oldValue) {
     const hasItemRemovedOrAdded = newValue.length !== oldValue.length
    }
  },
});

Check out the docs for more information about this.

Leave a comment