How can I watch an array length using Vue.js?
Asked
Active
Viewed 3.4k times
2 Answers
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
-
2Oh, you just saved me from some painfully hackish code with that idea of watching a computed length attribute! – Michael Cordingley May 03 '18 at 00:31
-
7more concisely `watch: { 'items.length'() { ... } }` – diachedelic Feb 18 '20 at 04:38
4
watch items.length in vue3 setup
import { watch } from "vue";
watch(
() => items.length,
(newValue,oldValue) => { console.log(newValue,oldValue)}
)

Alint Ever
- 41
- 1