模版可以放運算邏輯,但是不建議放太複雜的邏輯,會降低可讀性
有get
和set
可以使用
data
,就是監聽自己的變化進行更新,computed的get
就是監聽很多變數的變化進行更新 - by curt
//javascript var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // a computed getter reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') } } })
< p >Original message: "{ { data value } }"< /p >
Original message: "{{ message }}"
< p >Computed reversed message: "{ { function name } }"< /p >
Computed reversed message: "{{ reversedMessage }}"
computed比method快!computed有「快取住結果」,method沒有。
now: "{ { now } }"
now: "{{ now }}"//只是值
nowC: "{ { nowC } }"
nowC: "{{ nowC }}"用computed
nowM: "{ { nowM() } }"
nowM: "{{ nowM() }}"用methods, 要加括號
watching dataKey1
, when dataKey1
change, update dataKey2
{ { key } }
watch: { dataKey1: function (dataValue1) { this.dataKey2 = dataValue1 + ' ' + this.dataKey3 } }example
watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } }
fullName: { { fullName } }
fullName: {{ fullName }}
fullNameC: { { fullNameC } }
fullNameC: {{ fullNameC }}
firstName: { { firstName } }
firstName: {{ firstName }}
lastName: { { lastName } }
lastName: {{ lastName }}
像C#這樣的用法
computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } }
fullName: { { fullName } }
fullName: {{ fullName }}
firstName: { { firstName } }
firstName: {{ firstName }}
lastName: { { lastName } }
lastName: {{ lastName }}
非watch
不可的時候。
This is most useful when you want to perform asynchronous or expensive operations in response to changing data
watch implementAsk a yes/no question:
{{ answer }}
Ask a yes/no question:
{{ answer }}
觸發方式 | 呼叫方式 必須和變數同名? |
呼叫 | |
---|---|---|---|
data |
「變數」被賦值,渲染view | o | vue.value |
watch |
「同名的變數」被賦值就執行 | o | vue.value |
computed |
「取用的變數」被賦值就執行 | x | vue.xValue |
method |
被呼叫就執行 | x | vue.value() |