11_set.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="./js/vue.js"></script>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <h1>{{msg}}</h1>
  12. <h2>用户姓名{{person.name}}</h2>
  13. <h2>用户年龄{{person.age}}</h2>
  14. <h2>用户性别{{person.sex}}</h2>
  15. <button @click="addAttr">
  16. 添加属性
  17. </button>
  18. </div>
  19. <script>
  20. new Vue({
  21. el: '#app',
  22. data: {
  23. msg: 'hello vue',
  24. person:{
  25. name:'张三',
  26. age:18
  27. }
  28. },
  29. methods:{
  30. addAttr(){
  31. // vue2 中添加属性 没有响应式效果
  32. // this.person.age = 20;
  33. // this.person.sex='男'
  34. // vue2 中添加属性 可以使用set方法添加
  35. Vue.set(this.person,'sex','男')
  36. // set 中 第一个参数是要修改的对象 第二个参数是要添加属性名 第三个参数是属性值
  37. }
  38. }
  39. })
  40. </script>
  41. </body>
  42. </html>