17

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

nixklai
  • 579
  • 4
  • 7
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189

2 Answers2

37

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!');
});
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189
4

watch items.length in vue3 setup

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