7計算屬性和偵聽器
7.1計算屬性
模板內(nèi)的表達式非常便利,但是設(shè)計它們的初衷是用于簡單運算的。
在模板中放入太多的邏輯會讓模板過重且難以維護。
所以,對于任何復(fù)雜邏輯,你都應(yīng)當使用計算屬性。
基礎(chǔ)例子
<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('')
? ? }
? }
})
計算屬性緩存 vs 方法
我們可以通過在表達式中調(diào)用方法來達到同樣的效果:
<p>Reversed message: "{{ reversedMessage() }}"</p>
// 在組件中
methods: {
? reversedMessage: function () {
? ? return this.message.split('').reverse().join('')
? }
}
我們可以將同一函數(shù)定義為一個方法而不是一個計算屬性。兩種方式的最終結(jié)果確實是完全相同的。然而,不同的是計算屬性是基于它們的響應(yīng)式依賴進行緩存的。只在相關(guān)響應(yīng)式依賴發(fā)生改變時它們才會重新求值。這就意味著只要 message 還沒有發(fā)生改變,多次訪問 reversedMessage計算屬性會立即返回之前的計算結(jié)果,而不必再次執(zhí)行函數(shù)。
計算屬性 vs 偵聽屬性
Vue 提供了一種更通用的方式來觀察和響應(yīng) Vue 實例上的數(shù)據(jù)變動:偵聽屬性。當你有一些數(shù)據(jù)需要隨著其它數(shù)據(jù)變動而變動時,你很容易濫用 watch——特別是如果你之前使用過 AngularJS。然而,通常更好的做法是使用計算屬性而不是命令式的 watch 回調(diào)。細想一下這個例子:
<div id="demo">{{ fullName }}</div>
var vm = new Vue({
? el: '#demo',
? data: {
? ? firstName: 'Foo',
? ? lastName: 'Bar',
? ? fullName: 'Foo Bar'
? },
? watch: {
? ? firstName: function (val) {
? ? ? this.fullName = val + ' ' + this.lastName
? ? },
? ? lastName: function (val) {
? ? ? this.fullName = this.firstName + ' ' + val
? ? }
? }
})
上面代碼是命令式且重復(fù)的。將它與計算屬性的版本進行比較:
var vm = new Vue({
? el: '#demo',
? data: {
? ? firstName: 'Foo',
? ? lastName: 'Bar'
? },
? computed: {
? ? fullName: function () {
? ? ? return this.firstName + ' ' + this.lastName
? ? }
? }
})
計算屬性的 setter
計算屬性默認只有 getter ,不過在需要時你也可以提供一個 setter :
// ...
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]
? ? }
? }
}// ...
現(xiàn)在再運行 vm.fullName = 'John Doe' 時,setter 會被調(diào)用,vm.firstName 和 vm.lastName也會相應(yīng)地被更新。
7.2偵聽器
雖然計算屬性在大多數(shù)情況下更合適,但有時也需要一個自定義的偵聽器。這就是為什么 Vue 通過 watch 選項提供了一個更通用的方法,來響應(yīng)數(shù)據(jù)的變化。當需要在數(shù)據(jù)變化時執(zhí)行異步或開銷較大的操作時,這個方式是最有用的。
例如:
<div id="watch-example">
? <p>
? ? Ask a yes/no question:
? ? <input v-model="question">
? </p>
? <p>{{ answer }}</p>
</div>
<!-- 因為 AJAX 庫和通用工具的生態(tài)已經(jīng)相當豐富,Vue 核心代碼沒有重復(fù) -->
<!-- 提供這些功能以保持精簡。這也可以讓你自由選擇自己更熟悉的工具。 -->
https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js">
https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js">
<script>var watchExampleVM = new Vue({
? el: '#watch-example',
? data: {
? ? question: '',
? ? answer: 'I cannot give you an answer until you ask a question!'
? },
? watch: {
? ? // 如果 `question` 發(fā)生改變,這個函數(shù)就會運行
? ? question: function (newQuestion, oldQuestion) {
? ? ? this.answer = 'Waiting for you to stop typing...'
? ? ? this.debouncedGetAnswer()
? ? }
? },
? created: function () {
? ? // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數(shù)。
? ? // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率
? ? // AJAX 請求直到用戶輸入完畢才會發(fā)出。想要了解更多關(guān)于
? ? // `_.debounce` 函數(shù) (及其近親 `_.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>
在這個示例中,使用 watch 選項允許我們執(zhí)行異步操作 (訪問一個 API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結(jié)果前,設(shè)置中間狀態(tài)。這些都是計算屬性無法做到的。
除了 watch 選項之外,您還可以使用命令式的 vm.$watch API。
完整代碼:
7 計算屬性和偵聽器1
<!DOCTYPE html>
<html>
<head>
<title>計算屬性和偵聽器</title>
https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</head>
<body>
<div id="example">
? <p>Original message: "{{ message }}"</p>
? <p>Computed reversed message: "{{ reversedMessage }}"</p>
? <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
<script>
var vm = new Vue({
? el: '#example',
? data: {
? ? message: 'Hello'
? },
? computed: {
? ? // 計算屬性的 getter
? ? reversedMessage: function () {
alert("reversedMessage")
? ? ? // `this` 指向 vm 實例
? ? ? return this.message.split('').reverse().join('')
? ? }
? }
})
</script>
</body>
</html>
7 計算屬性和偵聽器2
<!DOCTYPE html>
<html>
<head>
<title>計算屬性和偵聽器</title>
https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</head>
<body>
<div id="example">
? <p>Reversed message: "{{ reversedMessage() }}"</p>
? <p>Reversed message: "{{ reversedMessage() }}"</p>
</div>
<script>
var vm = new Vue({
? el: '#example',
? data: {
? ? message: 'Hello'
? },
? methods: {
? ? reversedMessage: function () {
alert("reversedMessage")
? ? ? return this.message.split('').reverse().join('')
? ? }
? }
})
</script>
</body>
</html>
7 計算屬性和偵聽器3
<!DOCTYPE html>
<html>
<head>
<title>計算屬性和偵聽器</title>
https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</head>
<body>
<div id="demo">{{ fullName }}</div>
<script>
var vm = new Vue({
? el: '#demo',
? data: {
? ? firstName: 'Foo',
? ? lastName: 'Bar',
? ? fullName: 'Foo Bar'
? },
? watch: {
? ? firstName: function (val) {
? ? ? this.fullName = val + ' ' + this.lastName
? ? },
? ? lastName: function (val) {
? ? ? this.fullName = this.firstName + ' ' + val
? ? }
? }
})
</script>
</body>
</html>
7 計算屬性和偵聽器4
<!DOCTYPE html>
<html>
<head>
<title>計算屬性和偵聽器</title>
https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</head>
<body>
<div id="demo">{{ fullName }}</div>
<script>
var vm = new Vue({
? el: '#demo',
? data: {
? ? firstName: 'Foo',
? ? lastName: 'Bar'
? },
? computed: {
? ? fullName: function () {
? ? ? return this.firstName + ' ' + this.lastName
? ? }
? }
})
</script>
</body>
</html>
7 計算屬性和偵聽器5
<!DOCTYPE html>
<html>
<head>
<title>計算屬性和偵聽器</title>
https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</head>
<body>
<div id="demo">
? {{ fullName }}<br>
? {{ firstName }}<br>
? {{ lastName }}<br>
</div>
<script>
var vm = new Vue({
? el: '#demo',
? data: {
? ? firstName: 'Foo',
? ? lastName: 'Bar'
? },
? 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]
? ? ? }
? ? }
? }// ...
})
vm.fullName = 'John Doe'
</script>
</body>
</html>
7 計算屬性和偵聽器6
<!DOCTYPE html>
<html>
<head>
<title>計算屬性和偵聽器</title>
https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</head>
<body>
<div id="watch-example">
? <p>
? ? Ask a yes/no question:
? ? <input v-model="question">
? </p>
? <p>{{ answer }}</p>
</div>
<!-- 因為 AJAX 庫和通用工具的生態(tài)已經(jīng)相當豐富,Vue 核心代碼沒有重復(fù) -->
<!-- 提供這些功能以保持精簡。這也可以讓你自由選擇自己更熟悉的工具。 -->
https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js">
https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js">
<script>var watchExampleVM = new Vue({
? el: '#watch-example',
? data: {
? ? question: '',
? ? answer: 'I cannot give you an answer until you ask a question!'
? },
? watch: {
? ? // 如果 `question` 發(fā)生改變,這個函數(shù)就會運行
? ? question: function (newQuestion, oldQuestion) {
? ? ? this.answer = 'Waiting for you to stop typing...'
? ? ? this.debouncedGetAnswer()
? ? }
? },
? created: function () {
? ? // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數(shù)。
? ? // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率
? ? // AJAX 請求直到用戶輸入完畢才會發(fā)出。想要了解更多關(guān)于
? ? // `_.debounce` 函數(shù) (及其近親 `_.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>
</body>