列表渲染
1、案例1
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>列表渲染</title> </head> <body> <div id="app"> <!--在v-for里使用数组--> <ul> <li v-for="(item,index) in persons"> {{item.name}}---{{item.age}}---{{item.address}}---{{index}}--- <button @click="deleteFunc(index)">删除</button> <button @click="updateFunc(index,{name:'xiaofang',age:16,address:'安陆'})">更新</button> </li> </ul> <!--在v-for里使用对象--> <ul> <li v-for="(value,key) in person"> {{key}}---{{value}} </li> </ul> </div> <script src="../js/vue.js" type="text/javascript"></script> <script> /* vue只是监视了数组persons,默认对其里面的对象的改变并没有监视。 数组更新检测: Vue将被侦听的数组的变异方法进行了包裹,所以它们也将会触发视图更新。 这些被包裹过的方法包括: push() pop() shift() unshift() splice() sort() reverse() */ const vm = new Vue({ el: "#app", data: { persons: [ { "name": "liuyang", "age": 18, "address": "湖北" }, { "name": "zhangsan", "age": 28, "address": "广东" }, { "name": "xiaoming", "age": 19, "address": "北京" } ], person: { "name": "xiaoming", "age": 19, "address": "北京" } }, methods: { deleteFunc(idx) { //删除下标为idx的元素 this.persons.splice(idx, 1); }, updateFunc(idx, newPerson) { //删除下标为idx的元素,并在原来位置插入新元素 this.persons.splice(idx, 1, newPerson); } } }); </script> </body> </html>
相识是缘