<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>06_列表渲染</title>
</head>
<body>
<!--
1. 列表显示
数组: v-for / index
对象: v-for / key
2. 列表的更新显示
删除item
替换item
-->
<div id="demo">
<h2>测试: v-for 遍历数组</h2>
<ul>
<li v-for="(p, index) in persons" :key="index">
{{index}}--{{p.name}}--{{p.age}}
--<button @click="deleteP(index)">删除</button>
--<button @click="updateP(index, {name:'Cat', age: 16})">更新</button>
</li>
</ul>
<button @click="addP({name: 'xfzhang', age: 18})">添加</button>
<h2>测试: v-for 遍历对象</h2>
<ul>
<li v-for="(item, key) in persons[1]" :key="key">{{key}}={{item}}</li>
</ul>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
]
},
methods: {
deleteP (index) {
/*
此处的splice方法不是原生JS中的splice方法
试想,如果此处的splice方法是原生JS中的splice方法
那么,Vue本身只是监视了Persons的改变,没有监视数组内部数据的改变
所以页面应该不会发生变化
因此,此处的splice是对原生方法的包装(重写),内部要依次完成两件事
1、调用原生的splice方法
2、更新界面
因此,Vue重写了数组中的一系列改变数组内部数据的方法(先调用原生,然后更新界面)--->数组内部改变,界面自动变化
*/
this.persons.splice(index, 1)
},
updateP (index, newP) {
console.log('updateP', index, newP)
/*
下面这个操作是不行的
this.persons[index] = newP
因为并没有改变Persons本身
数组内部发生了变化,但并没有调用变异方法,vue不会更新界面
Vue本身只是监视了Persons的改变,没有监视数组内部数据的改变
*/
// this.persons[index] = newP
this.persons.splice(index, 1, newP)
// this.persons = []
},
addP (newP) {
this.persons.push(newP)
}
}
})
</script>
</body>
</html>