Vue.js: watch array length

25,906

Use the watch section in your vm creation:

var vm = new Vue({
    el: 'body',
    data: {
        items: []
    },
    computed: {
        item_length: function () {
            return this.battle_logs.length;
        }
    },
    watch: {
        items: {
            handler: function () {
                console.log('caught!');
            },
            deep: true
        }
    }
});

Or watch a computed length attribute:

vm.$watch('item_length', function(newVal, oldVal) {
    console.log('caught!');
});
Share:
25,906

Related videos on Youtube

Alfred Huang
Author by

Alfred Huang

一切有为法, 如梦幻泡影。 如露亦如电, 应作如是观。

Updated on October 27, 2021

Comments

  • Alfred Huang
    Alfred Huang over 2 years

    How can I watch an array length using Vue.js?

  • Michael Cordingley
    Michael Cordingley about 6 years
    Oh, you just saved me from some painfully hackish code with that idea of watching a computed length attribute!
  • diachedelic
    diachedelic about 4 years
    more concisely watch: { 'items.length'() { ... } }