## 一:計算屬性:訪問對象的值時,會觸發計算屬性(`computed`)中屬性相對應的方法。
計算屬性的本質是觸發對象的get方法。
對象存取器:
get:當訪問一個對象的屬性時將會觸發get方法
set:當設置一個對象的屬性時將會觸發set方法
### 例子:
~~~
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
~~~
~~~
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// 計算屬性的 getter
reversedMessage: function () {
// `this` 指向 vm 實例
return this.message.split('').reverse().join('')
}
}
})
~~~
## 二:監聽屬性:當data的值發生改變時,會觸發偵聽屬性(`watch`)中屬性相對應的方法。
### 例子:
~~~
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
~~~
~~~
<!-- 因為 AJAX 庫和通用工具的生態已經相當豐富,Vue 核心代碼沒有重復 -->
<!-- 提供這些功能以保持精簡。這也可以讓你自由選擇自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
? // 如果 `question` 發生改變,這個函數就會運行
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.debouncedGetAnswer()
}
},
created: function () {
? // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數。
? // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率
? // AJAX 請求直到用戶輸入完畢才會發出。想要了解更多關于
// `_.debounce` 函數 (及其近親 `_.throttle`) 的知識,
// 請參考:https://lodash.com/docs#debounce
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
methods: {
getAnswer: function () {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
}
}
})
</script>
~~~