对象的处理:(对于已经创建的实例,Vue 不允许动态添加根级别的响应式 property)
- Vue 无法检测 property (属性)的添加或移除。
由于vue会在初始化实例时对property执行getter/setter执行转化,
所以 property 必须在 data 对象上存在才能让 Vue 将它转换为响应式的。解决方式:全局: Vue.set(object, propertyName, value) 方法向嵌套对象添加响应式 property局部: this.$set(object, propertyName, value) 举例说明:
this.$set(this.someObject,'b',2)
Vue.set(this.someObject,'b',2)
- 为已有对象赋值多个新 property(属性)
使用 Object.assign() 或 _.extend();但是这样直接使用不会触发响应式的。// 代替 `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
对于数组
Vue 不能检测以下数组的变动:
- 当你利用索引直接设置一个数组项时:vm.items[index] = newValue
- 当你修改数组的长度时:vm.items.length = newLength
解决方案:
解决数组的第一个问题:// Vue.set(全局)
Vue.set(vm.items, indexOfItem, newValue)// vm.$set(局部)
vm.$set(vm.items, indexOfItem, newValue)// Array.prototype.splice (采用数组的原生方法)
vm.items.splice(indexOfItem, 1, newValue)解决数组的第二个问题:vm.items.splice(newLength) // 采用数组的原生方法
异步更新队列(this.$nextTick())
- 返回一个Promise对象
Vue.component('example', {template: '<span>{
{ message }}</span>',data: function () {return {message: '未更新'}},methods: {updateMessage: function () {this.message = '已更新'console.log(this.$el.textContent) // => '未更新'this.$nextTick(function () {console.log(this.$el.textContent) // => '已更新'})}}
})
- 可以用 ES2017 async/await 语法完成相同的事情
# async/await关键字要配对使用,不能单独使用哦methods: {updateMessage: async function () {this.message = '已更新'console.log(this.$el.textContent) // => '未更新'await this.$nextTick()console.log(this.$el.textContent) // => '已更新'}
}