1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>总结Vue数据监测</title> <script src="../resources/js/vue.js"></script> </head> <body> <div id="root"> <h1>学生信息</h1> <button @click="student.age++">年龄+1岁</button> <button @click="addGender">添加性别属性,默认值为男</button> <button @click="addFriend">在列表首位添加一个朋友</button> <button @click="updateFirstFriendName">修改第一个朋友的名字为“张三”</button> <button @click="addHobby">添加一个爱好</button> <button @click="modifyHobby">修改第一个爱好为“开车”</button> <button @click="filterSmoking">过滤掉爱好中的抽烟</button> <h2>学生姓名:{{student.name}}</h2> <h2 v-if="student.gender">学生性别:{{student.gender}}</h2> <h2>学生年龄:{{student.age}}</h2> <h2>学生爱好</h2> <ul> <li v-for="(h, index) in student.hobby"> {{h}} </li> </ul> <h2>朋友:</h2> <ul> <li v-for="(f,index) of student.friends" :key="index"> {{f.name}}--{{f.age}} </li> </ul> </div> </body> <script type="text/javascript"> Vue.config.productionTip = false; const vm = new Vue({ el:"#root", data:{ student:{ name:'Linzepore', age:18, hobby:['抽烟','喝酒','烫头'], friends:[ {name:'jack',age:30}, {name:'lily',age:20} ] } }, methods:{ addGender(){ // 错误写法 vm.set(this,student.gender,'男') // 另一种方式 Vue.set(this.student,'gender','男'), this.$set(this.student,'gender','男') }, addFriend(){ this.student.friends.unshift({name:'tom', age:13}) }, updateFirstFriendName(){ this.student.friends[0].name = '张三' }, addHobby(){ this.student.hobby.push('打台球') }, modifyHobby(){ // this.student.hobby.splice(0,1,'开车') Vue.set(this.student.hobby,0,'开车') }, filterSmoking(){ const newHobby = this.student.hobby.filter((val)=>{ return val != '抽烟' }) this.student.hobby = newHobby; } } }) </script> </html>
|