1. 列表显示
1.1数组: v-for / index
<h2>测试:v-for 遍历数组</h2>
<ul>
<li v-for="(p,index) in pesrons" :key="index">
{{index}}-----{{p.name}}----{{p.age}}
----<button @click="deletep(index)">删除</button>
----<button @click="updatep(index,{name:'cat',age:20})">更新</button>
</li>
</ul>
1.2对象: v-for / key(用的比较少)
<h2>测试:v-for 遍历对象</h2>
<ul>
<li v-for="(value,key) in pesrons[1]" :key="key">
{{value}}----{{key}}
</li>
</ul>
2.重点:
//vue 本身只是监视了pesons改变,没有监视数组内部数据的改变=》变异
//vue重写了数组中的一系列改变数组内部数据的方法(先调用原生,更新界面)----》数组内部改变,界面自动变化
methods:{
deletep(index){
//删除persons中指定的index的p=》数组重写
this.pesrons.splice(index,1)
},
updatep(index,newP){
//this.pesrons[index]=newP 没有改变pesons本身,数组内部发生变化,但没有调用变异方法,vue不会更新界面
this.pesrons.splice(index,1,newP)
}
}
3.全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>06_列表渲染</title>
</head>
<body>
<div id="demo">
<h2>测试:v-for 遍历数组</h2>
<ul>
<li v-for="(p,index) in pesrons" :key="index">
{{index}}-----{{p.name}}----{{p.age}}
----<button @click="deletep(index)">删除</button>
----<button @click="updatep(index,{name:'cat',age:20})">更新</button>
</li>
</ul>
<h2>测试:v-for 遍历对象</h2>
<ul>
<li v-for="(value,key) in pesrons[1]" :key="key">
{{value}}----{{key}}
</li>
</ul>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
//vue 本身只是监视了pesons改变,没有监视数组内部数据的改变=》变异
//vue重写了数组中的一系列改变数组内部数据的方法(先调用原生,更新界面)----》数组内部改变,界面自动变化
new Vue({
el:"#demo",
data:{
pesrons:[
{name:'Tom',age:18},
{name:'Jack',age:16},
{name:'Bob',age:19},
{name:'Rose',age:17},
]
},
methods:{
deletep(index){
//删除persons中指定的index的p=》数组重写
this.pesrons.splice(index,1)
},
updatep(index,newP){
//this.pesrons[index]=newP 没有改变pesons本身,数组内部发生变化,但没有调用变异方法,vue不会更新界面
this.pesrons.splice(index,1,newP)
}
}
})
</script>
</body>
</html>