9_计算属性.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. <span>{{num1}}</span> + <span>{{num2}}</span> = <span>{{num3}}</span>
  11. <br>
  12. <button @click="changeNum1">num1++</button>
  13. <button @click="num2++">num2++</button>
  14. </div>
  15. <script src="./js/vue.js"></script>
  16. <script>
  17. new Vue({
  18. el:"#app",
  19. data:{
  20. num1:1,
  21. num2:2,
  22. // num3:3
  23. },
  24. methods:{
  25. changeNum1(){
  26. this.num1++;
  27. this.num3 = this.num1 + this.num2;
  28. // this.num3 = this.num1 + this.num2;
  29. }
  30. },
  31. // computed 计算属性
  32. // 如果当前计算属性所依赖的值发生变化,那么计算属性会自动重新计算
  33. computed:{
  34. num3(){
  35. console.log("num3被计算了");
  36. return this.num1 + this.num2;
  37. }
  38. // num3:{
  39. // get(){
  40. // console.log("num3被计算了");
  41. // return this.num1 + this.num2;
  42. // },
  43. // set(val){
  44. // console.log("num3被设置为了" + val);
  45. // }
  46. // }
  47. }
  48. })
  49. </script>
  50. </body>
  51. </html>