Vue的缺点.不能检测到新对象属性的添加和删除.
<template>
<div>
{
{ obj }}
<button @click='hand'>按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
obj: {
name: 1
}
}
},
methods: {
han() {
this.obj.name2 = new Date()
}
}
}
</script>
当事件触发的时候页面渲染的obj是不会有变化的.
1.方法$set
<template>
<div>
{
{ obj }}
<button @click='hand'>按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
obj: {
name: 1
}
}
},
methods: {
han() {
// this.obj.name2 = new Date() !~当使用$set方法的时候.就不要使用原始方法.会出现读取第一步.已经存在而不继续读取
// this.$set 有三个参数.分别是.
// this.$set(当前所需要添加对象所在的具体地方,'当前添加对象的名',值)
this.$set(this.obj, 'name2', new Date())
}
}
}
</script>
2.方法2.
通过设置v-if='xxx' 初始默认为true, 在执行事件的时候隐藏部分状态,
再利用this.$nextTick()等待异步任务完全执行完毕以后重现渲染部分页面.
<template>
<div>
<div v-if="show">{
{ obj }}</div>
<button @click="han">按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
show: true,
obj: {
name: 1
}
}
},
methods: {
han() {
this.show = false
this.obj.name2 = new Date()
this.$nextTick(() => {
this.show = true
})
}
}
}
</script>
<style>
</style>
注意点:
一般通用第二种方法,第一种方法虽然可以实现.但是如果属性量过大.那么操作起来太困难