Vue监视数据的原理:
- Vue会监视data中所有层次的数据。
- 如何监测对象中的数据?
通过setter实现监视,且要在 new Vue时就传入要监测的数据。
(1)对象中后追加的属性,Vue默认不做响应式处理。
(2)如需给后追加的属性做响应式,请使用如下API:
- Vue.set(target,propertyName/index,value) 或
- vm.$set(target,propertyName/index,value)
例如:
Vue.set(this.student,'sex','男');
vm.$set(this.student,'sex','男');
- 如何监测数组中的数据?
通过包裹数组更新元素的方法实现,本质就是做了两件事:
(1)调用原生对应的方法对数组进行更新。
(2)重新解析模板,进而更新页面。
- 在Vue中修改数组中的某个元素一定要用如下方法:
(1)七个数组API: push(),pop(),shift(),unshift(),splice(),sort(),reverse()
(2)Vue.set()或vm.$set()
特别注意:
Vue.set()和vm.$set()不能给vm或vm的根数据对象(._data)添加属性。
实例:
<div id="app">
<button @click="addMarry">点击添加婚姻状态</button>
<button @click=" student.marry='已婚' ">点击修改婚姻状态</button>
<button @click="addPosition">点击添加职位</button>
<button @click="updateFriendName">修改第一个朋友名字</button>
<button @click="addHobby">添加爱好</button>
<button @click="updateHobby">修改第一个爱好</button>
<h3>姓名:{{student.name}}</h3>
<h3>年龄:{{student.age}}</h3>
<h3>性别:{{student.sex}}</h3>
<h3 v-if="student.marry">婚姻状态:{{student.marry}}</h3>
<h3 v-if="student.position">职位:{{student.position}}</h3>
<ul>
<li v-for="(item,index) in student.hobby" :key="index">{{item}}</li>
</ul>
<div v-for="(f,index) in student.friends" :key="index">
朋友: 姓名:{{f.name}} 年龄:{{f.age}} 性别:{{f.sex}}
<ul>
<li v-for="(h,index) in student.friends[index].hobby" :key="index">
{{h}}
</li>
</ul>
</div>
</div>
<script src="./vue.js"></script>
<script>
Vue.config.productionTip = false;
let vm = new Vue({
el: '#app',
data() {
return {
student: {
name: '马冬梅',
age: 28,
sex: '女',
hobby: ['踢球', '打球', '看球'],
friends: [
{
name: '赵铁蛋',
age: 28,
sex: '男',
hobby: ['买球', '卖球', '拍球'],
},
{
name: '王老五',
age: 58,
sex: '男',
hobby: ['唱', '跳', '拍球'],
},
],
},
};
},
methods: {
addMarry() {
Vue.set(this.student, 'marry', '未婚');
},
addPosition() {
this.$set(this.student, 'position', '前端开发'); //vm和this用$set效果相同,Vue用set
},
updateFriendName() {
this.student.friends[0].name = '张三';
},
addHobby() {
this.student.hobby.push('学习');
},
updateHobby() {
// this.$set(this.student.hobby, 0, '开车');
this.student.hobby.splice(0, 1, '买车'); //从索引0开始,删除到索引1
},
},
});
</script>```