<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<!--
Vue监视数据原理
1.vue会监视data中所有层次的数据
2.如何监视对象中数据
通过setter实现监视,切要在new Vue时就传入要检测的数据
(1).对象中后追加的属性,vue默认不做响应式处理
(2)。如需给后添加的属性做襄阳市,请使用下面APL:
Vue.set(target,propertyName/index,value)或
vm.$set(target,propertyName/index,value)
3.如何监视数据中数据
通过包括数组更新元素的方法实现,本本质就是做了两件事
(1)调用原声对应的方法对数组进行更新
(2)重新解析模板,进而更新页面
4.在vue修改数组中的某个元素一定要用如下方法:
1.
push() 末尾添加
pop()
shift()
unshift()
splice()
sort()
reverse()
2.第二种解决方法
Vue.set(vm._data.hobby.push,0,'睡觉')
vm._data.hobby.push('学习')
vm.$set(vm.hobby,0,'放屁1')
特别注意:Vue.set()和vm.$set()不能给vm或vm的跟数据对象添加属性
数据劫持:修改了值,重新进行解析,并回显页面上
-->
<script src="vue.js"></script>
</head>
<body>
<div id="root">
<h1>学生信息</h1>
<button @click="student.age++">年龄+1岁</button>
<button @click="addSex">添加性别属性,默认值:男</button>
<button @click="student.sex = ' 女' ">修改性别</button>
<button @click='addFrient'>在列表首位添加一个朋友</button>
<button @click="insertSplice">修改第一个朋友的名字为:张三</button>
<button @click="hobb">添加一个爱好</button>
<button @click="upca">修改第一个爱好为:开车</button>
<h3>姓名:{{student.name}}</h3>
<h3>年龄:{{student.age}}</h3>
<h3 v-if="student.sex">性别:{{student.sex}}</h3>
<h3>爱好:</h3>
<ul>
<li v-for="(h,index) in student.hobby" :key = index>
{{h}}
</li>
</ul>
<h3>朋友们</h3>
<ul>
<li v-for="(f,index) in student.friends" :key="index">
{{f.name}}-{{f.age}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false
const vm = new Vue({
el:'#root',
data:{
student:{
name:'tom',
age:18,
hobby:['抽烟','喝酒','打架'],
friends:[
{name:'jerry',age:35},
{name:'tony',age:36}
]
}
},
methods:{
addSex(){
Vue.set(this._data.student,'sex','男')
},
addFrient(){
this._data.student.friends.unshift({name:'peng',age:'99'})
},
insertSplice(){
this._data.student.friends[0].name = '张三'
},
hobb(){
this.student.hobby.push('学习')
},
upca(){
this.student.hobby.splice(0,1,'开车')
}
}
})
</script>
</body>
</html>