17

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

2 Answers 2

39

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!');
});
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, you just saved me from some painfully hackish code with that idea of watching a computed length attribute!
more concisely watch: { 'items.length'() { ... } }
5

watch items.length in vue3 setup

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.