11.计算属性.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. 姓:<input v-model="firstName" type="text">
  11. 名:<input v-model="lastName" type="text">
  12. <br><br>
  13. <!-- 1. 插值模板-->
  14. 我的姓名是:{{firstName + lastName}}
  15. <br>
  16. <!-- 2.方法 -->
  17. 我的姓名是:{{getName()}}
  18. <br>
  19. <!-- 3.计算属性 -->
  20. 我的姓名是:{{myName}}{{full}}
  21. <button @click="changeMain">修改</button>
  22. <!-- 4.侦听器 / 监听器 -->
  23. <br>
  24. 我的姓名是:{{fullName}}
  25. </div>
  26. <script src="./vue.js"></script>
  27. <script>
  28. var app = new Vue({
  29. data:{
  30. firstName:"孙",
  31. lastName:"悟空",
  32. part1: "娃",
  33. part2: "哈哈",
  34. fullName:"哈哈哈"
  35. },
  36. methods: {
  37. getName() {
  38. return this.firstName + this.lastName
  39. },
  40. changeMain() {
  41. this.myName = ''
  42. }
  43. },
  44. /**
  45. * 计算属性 computed
  46. * 原理:通过Object.defineProperty()中getter和setter 获取数据 修改数据
  47. * methods 和 computed 初始化使用时没有什么区别
  48. * 当数据发生改变 会执行代码进行处理 减少性能消耗
  49. * 同步操作
  50. * 有缓存
  51. */
  52. computed:{
  53. myName:{
  54. get() {
  55. return this.part1 + this.part2
  56. },
  57. set() {
  58. this.part1 = '百'
  59. this.part2 = '岁山'
  60. }
  61. },
  62. full() {
  63. return this.aaa = '111';
  64. }
  65. },
  66. /**
  67. * watch 侦听器 监听器
  68. * immediate 立即监听
  69. * deep 深度监听
  70. * handle(newValue,oldValue) {执行语句}
  71. * 异步操作
  72. * 没有缓存
  73. */
  74. watch:{
  75. firstName(newValue,oldValue) {
  76. // console.log(newValue,oldValue)
  77. this.fullName = newValue + this.lastName
  78. },
  79. lastName(newValue,oldValue) {
  80. // console.log(newValue,oldValue)
  81. this.fullName = this.firstName + newValue
  82. },
  83. fullName:{
  84. immediate: true,
  85. deep: true,
  86. handler(newValue,oldValue) {
  87. console.log(newValue,'new')
  88. console.log(oldValue,'oldValue')
  89. // if(newValue) {
  90. // alert(newValue)
  91. // } else {
  92. // alert("请输入姓名")
  93. // }
  94. }
  95. }
  96. }
  97. }).$mount("#app");
  98. </script>
  99. </body>
  100. </html>