Vue不能检测对象属性的添加和删除,要是必须这么做的话
需要使用 vue.$set()
<body>
<div id="app">
<h3>
{{user.name}}
{{user.age}} <!--this.user.age=20 这个是不会成功的-->
</h3>
<button @click="handlerAdd">添加属性</button>
</div>
<script>
// vue 不能检测对象属性的添加和删除
// 要用 vue的方法 Vue.set
let app = new Vue({
el:'#app',
data:{
user:''
},
methods:{
handlerAdd(){
// vue.$set(object,key,value)
this.$set(this.user,'age',20)
// this.user.age=20 这个是不会成功的
}
},
created(){
setTimeout(()=>{
this.user={
name:'张三'
}
},1250)
}
})
</script>
</body>
添加多个响应式属性
<h3> {{user.name}} {{user.phone}} {{user.age}} <!--this.user.age=20 这个是不会成功的--> </h3>
handlerAdd(){ // 添加多个响应式 this.user = Object.assign({},this.user,{ age:20, phone:13811091109 }) }