Vue2.0 之 Vue.set 向响应式对象中添加一个响应式属性

Vue不能检测到对象属性的添加或删除。由于Vue会在初始化实例时对属性执行getter/setter转化过程,所以属性必须在data对象上存在才能让Vue转换它,这样才能是响应式的。例如:

data () {
    return {
        form: {
            total: 10
        }
    }
}

// this.form.total是响应式的

// 若直接增加属性,是非响应式的
this.form.showFlag= true  //非响应式的

使用Vue.set(object, key, value)方法将响应属性添加到嵌套的对象上

Vue.set(this.form, 'showFlag', true)

还可以使用vm.$set实例方法,这也是全局Vue.set方法的别名:

this.$set(this.form, 'showFlag', true)

猜你喜欢

转载自blog.csdn.net/amyleeYMY/article/details/81162479