【问题标题】:Vue.js: watch array lengthVue.js:观察数组长度
【发布时间】:2016-08-30 17:13:00
【问题描述】:

如何使用 Vue.js 观察数组长度?

【问题讨论】:

    标签: javascript mvvm ecmascript-6 vue.js


    【解决方案1】:

    在创建虚拟机时使用 watch 部分:

    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
            }
        }
    });
    

    或者观察一个计算出来的长度属性:

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

    【讨论】:

    • 哦,你刚刚用观察计算长度属性的想法把我从一些令人痛苦的黑客代码中救了出来!
    • 更简洁watch: { 'items.length'() { ... } }
    【解决方案2】:

    在 vue3 设置中查看 items.length

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 2021-02-19
      • 2019-03-01
      • 2017-05-22
      • 2019-05-11
      • 2017-10-24
      相关资源
      最近更新 更多