3.计算属性.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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>姓名是: {{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. return this.newName + '-' + this.liName;
  60. },
  61. set() {
  62. this.newName = "天气";
  63. this.liName = "真好";
  64. }
  65. }
  66. },
  67. // watch:{
  68. // // 初次进入页面 并不监听 发生更改才会开启监听
  69. // newName(newValue,oldValue) {
  70. // this.full = newValue + this.liName;
  71. // },
  72. // liName(newValue,oldValue) {
  73. // this.full = this.newName + newValue;
  74. // },
  75. // // 如果我们想 初始化页面进行监听
  76. // // 补充知识点
  77. // // newName: {
  78. // // // 开启监听 , 深度监听
  79. // // immediate:true,
  80. // // deep: true,
  81. // // handler() {
  82. // // }
  83. // // }
  84. // },
  85. // 自定义的方法
  86. methods: {
  87. getFullName() {
  88. // this => Vue实例
  89. return this.firstName + this.lastName + this.full;
  90. }
  91. },
  92. })
  93. // 解决set失效问题
  94. vm.myName = '';
  95. </script>
  96. </body>
  97. </html>