Vue.js: watch array length

35.6k Views Asked by At

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

2

There are 2 best solutions below

2
Alfred Huang On BEST ANSWER

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!');
});
0
Alint Ever On

watch items.length in vue3 setup

import { watch } from "vue";
watch(
  () => items.length,
  (newValue,oldValue) => { console.log(newValue,oldValue)}
)