【Vue】|【Vue】 计算属性

1. 计算属性computed:应用于复杂逻辑运算的一种属性 模版内的表达式非常便利,但是表达式的逻辑运算太多会使模板过重且难以维护,所以模板中任何复杂逻辑都应当使用计算属性。

  • 使用模板语法中方法methods和 计算属性computed的区别展示:
//html{{computedMessage}} {{computedMessage}} {{computedMessage}} {{calcMessage()}} {{calcMessage()}} {{calcMessage()}}

//js代码 var app = new Vue({ el: '#app', data: { message: 'hi' }, computed:{ computedMessage(){ console.log('computed') return 'computed ' + this.message }, }, methods:{ calcMessage(){ console.log('methods') return 'calc ' + this.message } } })

上述代码打印了一次 computed,三次 methods
2. 侦听器watch Vue使用了一种普通的方法来观察和响应Vue实例上数据变动的属性称为侦听器
  • 当有些数据伴随着其他数据二变化时,通常最好用的方法就是计算属性而不是命令式地watch回调。
  • 使用侦听器的例子:
//html{{count}} 你改了 {{modified}} 次

//js var app = new Vue({ el: '#app', data: { count: 1, modified: 0 }, watch:{ count(){ this.modified += 1 } } })

【【Vue】|【Vue】 计算属性】点击次数之和等于modefied的值

    推荐阅读