<div id="app">
<button @click="change()">修改</button>
<p>{{ arr }}</p>
<p>{{ user }}</p>
<p>{{ userInfo }}</p>
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
arr: [1,12,34,5,1],
user: [
{name: 'Sean', age: 20},
{name: 'Zan', age: 3}
],
userInfo:{
name: 'Billy'
}
},
methods:{
change() {
//1. 将arr数组中索引为1的值修改为'zan'
Vue.set(this.arr, 1, 'zan'),
//2. 给user数组添加对象
Vue.set(this.user, 2, {name: 'Billy', age: 10}),
//3. 修改user数组索引为0的对象属性值
Vue.set(this.user, 0, {name: 'Jim', age: 42}),
//4. 给对象添加属性
// Vue.set(this.userInfo.age, 18) //这种写法不正确
Vue.set(this.userInfo, 'age', 29)
}
}
})
</script>
运行结果:
修改前
修改后