3.计算属性.html 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <script src="../../vue.js"></script>
  9. </head>
  10. <body>
  11. <div id="app">
  12. <!-- 第一种实现:通过插值语法中表达式 (只能完成简单的逻辑运算) -->
  13. <p>(1)我的姓名是:<b>{{ firstname + lastname }}</b></p>
  14. <!-- 第二种实现:通过vm方法 (简单或者复杂的逻辑都可以实现)-->
  15. <p>(2)我的姓名是:<b>{{ getFullname() }}</b></p>
  16. <!-- 第三种实现:通过Vue的计算属性:有缓存 -->
  17. <!-- 计算属性 定义时为方法;使用时为属性。 -->
  18. <!-- 计算属性,必须是同步任务,必须即刻有返回值。同时为了提高页面性能,尽量不要在计算属性里编写计算量大且耗时的代码 -->
  19. <p>(3)我的姓名是:<b>{{ fullname }}</b></p>
  20. <p>实际开发时,如何去使用计算属性?</p>
  21. <p>第一,尽量多的去使用计算属性(如果可以的话)</p>
  22. <p>
  23. 第二,如果需要再原有数据上生成新的数据(衍生数据),此时大概率是计算属性。
  24. </p>
  25. <p>
  26. 第三,如果计算属性中,需要编写异步或者耗时比较大的代码时,不要选择计算属性,可以通过监听器来实现
  27. </p>
  28. <p>(4)我的姓名是:<b>{{ full }}</b></p>
  29. </div>
  30. <script>
  31. var vm = new Vue({
  32. el: '#app',
  33. data: {
  34. firstname: '郭',
  35. lastname: '靖',
  36. full: '郭靖',
  37. },
  38. // 在参数对象中的watch里定义监听器
  39. watch: {
  40. firstname(newValue, oldValue) {
  41. // 所有监听器中 this 也是 Vue实例(vm)
  42. // 一旦 firstname 变化了,那么该监听器就会执行。同时接受两个参数,分为 新值 和 旧值。
  43. this.full = newValue + this.lastname;
  44. }, // 就是 firstname 监听器
  45. lastname(newValue, oldValue) {
  46. this.full = this.firstname + newValue;
  47. }, // 就是 lastname 监听器
  48. },
  49. // 在参数对象中的computed属性里定义计算属性,所有计算属性本质 都是 函数
  50. computed: {
  51. fullname() {
  52. // 所有计算属性 中 this 的值 都是 Vue实例(vm), 同时必须有返回值
  53. return this.firstname + this.lastname;
  54. },
  55. },
  56. methods: {
  57. getFullname() {
  58. // 在方法中,this 就是 Vue实例 (vm)
  59. return this.firstname + this.lastname;
  60. },
  61. },
  62. });
  63. </script>
  64. </body>
  65. </html>