3.计算属性.html 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. </head>
  8. <body>
  9. <div id="app">
  10. <div>
  11. <p>
  12. 姓:<input type="text" v-model="newName">
  13. </p>
  14. <p>
  15. 名:<input type="text" v-model="liName">
  16. </p>
  17. <p @click="getName()">姓名是: {{myName}}</p>
  18. </div>
  19. <p>名字是:{{firstName + lastName}}</p>
  20. <p>我们的名字是:{{ getFullName() }}</p>
  21. <p>{{full}}</p>
  22. <!--
  23. 计算属性
  24. -->
  25. <h1 style="color: red;">我们的名字是:{{fullName}}</h1>
  26. <p>
  27. 1.最好大量的去使用计算属性 计算属性有缓存 同步操作 处理计算量不大的数据
  28. </p>
  29. <p>
  30. 2.像数据进行更新(衍生数据),最好使用计算属性
  31. </p>
  32. <p>
  33. 3.如果计算量大 消耗性能 异步操作 使用侦听器(watch)
  34. </p>
  35. <p>
  36. 4.watch 不进行缓存 计算量大的操作 异步操作
  37. </p>
  38. </div>
  39. <script src="./vue.js"></script>
  40. <script>
  41. var vm = new Vue({
  42. el:"#app",
  43. data:{
  44. firstName: '卢勃玮',
  45. lastName: '张振博',
  46. full: '马琛',
  47. newName: '马',
  48. liName: '琛',
  49. },
  50. computed:{
  51. fullName() {
  52. console.log("获取get的值")
  53. // 抛出数据 return 返回值;
  54. return this.firstName + this.lastName + this.full;
  55. },
  56. myName:{
  57. // 走的是getter 实际get方法
  58. get(){
  59. console.log(this.newName,'获取1');
  60. console.log(this.liName,'获取2');
  61. return this.newName + '-' + this.liName;
  62. },
  63. set(value) {
  64. console.log(value,'获取set值');
  65. const arr = value.split('-');
  66. this.newName = arr[1];
  67. this.liName = arr[0];
  68. console.log("set设置")
  69. }
  70. }
  71. },
  72. watch:{
  73. // 初次进入页面 并不监听 发生更改才会开启监听
  74. newName(newValue,oldValue) {
  75. this.full = newValue + this.liName;
  76. },
  77. liName(newValue,oldValue) {
  78. this.full = this.newName + newValue;
  79. },
  80. // 如果我们想 初始化页面进行监听
  81. // 补充知识点
  82. // newValue: {
  83. // // 开启监听 , 深度监听
  84. // immediate:true,
  85. // deep: true,
  86. // handler() {
  87. // }
  88. // }
  89. },
  90. // 自定义的方法
  91. methods: {
  92. getFullName() {
  93. // this => Vue实例
  94. return this.firstName + this.lastName + this.full;
  95. },
  96. getName() {
  97. console.log(this.newName);
  98. console.log(this.liName);
  99. }
  100. },
  101. })
  102. </script>
  103. </body>
  104. </html>