4_vue数据监测.html 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <link rel="icon" href="../../logo.svg" />
  8. <title>vue数据监测</title>
  9. </head>
  10. <body>
  11. <div id="root">
  12. <h1>学生信息</h1>
  13. <div>
  14. <button @click="incrementAge">年龄+1岁</button>
  15. <button @click.once="addGender">添加性别</button>
  16. <button @click="updateGender">修改性别</button>
  17. <button @click.once="addFriend">在第1个位置添加朋友</button>
  18. <button @click.once="updateFirstFriend">
  19. 修改第一个朋友的名字为张三
  20. </button>
  21. <button @click.once="addHobby">添加一个爱好</button>
  22. <button @click.once="updateFirstHobby">修改第一个爱好为开车</button>
  23. </div>
  24. <div>姓名:{{student.name}}</div>
  25. <div>年龄:{{student.age}}</div>
  26. <div v-if="student.gender">年龄:{{student.gender}}</div>
  27. <h2>爱好</h2>
  28. <ul>
  29. <li v-for="(h,idx) in student.hobby" :key="idx">{{h}}</li>
  30. </ul>
  31. <h2>好友</h2>
  32. <ul>
  33. <li v-for="(f,idx) in student.friends" :key="idx">
  34. {{f.name}} - {{f.age}}
  35. </li>
  36. </ul>
  37. </div>
  38. <script src="../../vue.js"></script>
  39. <script>
  40. Vue.config.productionTip = false; // 阻止 vue 在启动时生成生产提示。
  41. const vm = new Vue({
  42. el: "#root",
  43. data: {
  44. student: {
  45. name: "yesen",
  46. age: 19,
  47. hobby: ["抽烟", "喝酒", "烫头"],
  48. friends: [
  49. { name: "jerry", age: 32 },
  50. { name: "tony", age: 41 },
  51. ],
  52. },
  53. },
  54. methods: {
  55. incrementAge() {
  56. this.student.age++;
  57. },
  58. addGender() {
  59. // this.$set(this.student, "gender", "男");
  60. this.student = { ...this.student, gender: "男" };
  61. },
  62. updateGender() {
  63. if (!this.student.gender) {
  64. this.addGender();
  65. }
  66. this.student.gender = "女";
  67. },
  68. addFriend() {
  69. // this.student.friends.unshift({ name: "王一", age: 21 });
  70. this.student.friends = [
  71. { name: "王一", age: 21 },
  72. ...this.student.friends,
  73. ];
  74. },
  75. updateFirstFriend() {
  76. // this.student.friends.splice(0, 1, {
  77. // ...this.student.friends[0],
  78. // name: "张三",
  79. // });
  80. // Vue.set(this.student.friends, 0, {
  81. // ...this.student.friends[0],
  82. // name: "张三",
  83. // });
  84. this.student.friends[0].name = "张三";
  85. },
  86. addHobby() {
  87. // this.student.hobby.push("刷剧");
  88. this.student.hobby = [...this.student.hobby, "刷剧"];
  89. },
  90. updateFirstHobby() {
  91. // this.student.hobby.splice(0, 1, "开车");
  92. this.$set(this.student.hobby, 0, "开车");
  93. },
  94. },
  95. });
  96. </script>
  97. </body>
  98. </html>