10.计算属性和侦听器.html 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. <style>
  8. .size {
  9. width: 400px;
  10. height: 400px;
  11. margin: 200px auto;
  12. border: 1px solid darksalmon;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div id="app">
  18. <div :class="['size']">
  19. 姓:
  20. <input type="text" v-model="firstName">
  21. <br>
  22. 名:
  23. <input type="text" v-model="lastName">
  24. <br>
  25. <!-- 1.插值语法 -->
  26. 我叫: {{firstName + lastName}}
  27. <br>
  28. <!-- 2.methods方法 -->
  29. 我叫:{{getName()}}
  30. <br>
  31. <!-- 3.计算属性:computed -->
  32. 我叫:{{fullName}}
  33. <br>
  34. 新名字:{{myName}}
  35. <br>
  36. <!-- 4.侦听器 -->
  37. 我叫:{{fulls}}
  38. </div>
  39. </div>
  40. <!--
  41. 原理:通过数据劫持(Object.defineproperty) 通过getter(get)和setter(set)实现获取数据 修改数据操作
  42. methods 与 computed 大致相同
  43. 但是:大量的计算数据 需要在计算属性中进行操作
  44. 计算数据写在computed里 性能较快 同步操作
  45. watch 异步操作
  46. -->
  47. <script src="./vue.js"></script>
  48. <script>
  49. //
  50. var app = new Vue({
  51. el:"#app",
  52. data:{
  53. firstName:"胡",
  54. lastName:"图图",
  55. news:"喜",
  56. old:"羊羊",
  57. fulls:""
  58. },
  59. methods: {
  60. getName() {
  61. return this.firstName + this.lastName
  62. }
  63. },
  64. // 计算属性
  65. computed:{
  66. fullName() {
  67. return this.firstName + this.lastName;
  68. },
  69. // myName() {
  70. // // get() {},
  71. // // set() {}
  72. // }
  73. myName: {
  74. get() {
  75. return this.news + this.old;
  76. },
  77. set() {
  78. this.news = '灰';
  79. this.old = '太郎'
  80. }
  81. }
  82. },
  83. watch:{
  84. // firstName(newValue,oldValue) {
  85. // this.fulls = newValue + this.lastName
  86. // },
  87. // lastName(newValue, oldValue) {
  88. // this.fulls =this.firstName + newValue;
  89. // },
  90. // 补充知识点:
  91. // myName:{
  92. // immediate: true,
  93. // deep: true,
  94. // handler(a) {
  95. // // 方法
  96. // console.log(a,'aaaa')
  97. // return this.fulls = a;
  98. // }
  99. // },
  100. firstName:{
  101. // 开启立即监听
  102. immediate: true,
  103. // 开启深度监听
  104. deep: true,
  105. handler(e) {
  106. // 方法
  107. console.log(e,'aaaa')
  108. return this.fulls = e + this.lastName;
  109. }
  110. },
  111. lastName:{
  112. immediate: true,
  113. deep: true,
  114. handler(e) {
  115. // 方法
  116. console.log(e,'aaaa')
  117. return this.fulls = this.firstName + e;
  118. }
  119. }
  120. }
  121. })
  122. // app.myName = ''
  123. </script>
  124. </body>
  125. </html>