Array array:
Due to JavaScript restriction, Vue can not detect changes in the following array:
- When you use the index directly to set an array item, such as:
vm.items[indexOfItem] = newValue
- When you modify the length of the array, for example:
vm.items.length = newLength
数组:
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // 不是响应性的
vm.items.length = 2 // 不是响应性的
Object object:
Or because JavaScript limitation, Vue can not detect the object's properties to add or remove :
For instance has been created, Vue allowed to dynamically add the root level of responsive property.
method:
1. For the example has been created, Vue allowed dynamically add the root level responsive properties. However, it may be used
Vue.set(object, propertyName, value)
a method of adding attributes to the nested object responsive.2. use
vm.$set
instance method, it is only the globalVue.set
alias: this.$set(object, propertyName, value)
3. assign multiple new attributes to an existing object, such as the use of
Object.assign()
or_.extend()
1. 采用全局Vue,可以添加一个新的 age 属性到嵌套的 userProfile 对象:
前提是当前页面引入Vue.js;
Vue.set(vm.userProfile, 'age', 27)
2. 可以使用 vm.$set 实例方法,它只是全局 Vue.set 的别名:
vm.$set(vm.userProfile, 'age', 27);
或
this.$set(vm.userProfile, 'age', 27)
3. 为已有对象赋值多个新属性,比如使用 Object.assign() 或 _.extend()。
在这种情况下,你应该用两个对象的属性创建一个新的对象
应该这样做:
vm.userProfile = Object.assign({}, vm.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})
Actual examples are as follows:
methods: {
say() {
if (!this.msg.hasOwnProperty('b')) { // 判断对象中是否含有b这个属性,hasOwnProperty()判断属性名是否存在
// this.$set(this.msg, 'b', 0); // 是响应式的
// this.msg = Object.assign({}, this.msg, { // 这一种方式是处理添加多个属性时候采用的方式
// b: 0,
// c: '小李子'
// })
// this.msg.b = 0 // 直接修改不会更新页面,不是响应式的
}
this.msg.b += 1
console.log(this.msg)
}
},