Vue 计算属性与侦听器
這一節(jié)我們一起學(xué)習(xí) vue 中的計算屬性(computed properties)和偵聽器(watch)。
在之前,我們學(xué)習(xí)過 vue 表達(dá)式插值:
<div id="example">{{ message.split('').reverse().join('') }} </div>如果在模板中放入太多的邏輯會讓模板過重且難以維護(hù)。我們可以把方法寫在事件處理函數(shù)里面,并且在構(gòu)造器內(nèi)部通過 this 調(diào)用。
<!-- more -->
Html 代碼:
JS 代碼:
methods: {reversedMessageMethod() {return this.message.split('').reverse().join('');}, }, 這里要提醒一下,我們不可以把事件處理函數(shù)寫成箭頭函數(shù),因為這里的 this 需要指向 vue 實例。一、過濾器
其實,模板中的處理邏輯是不適合放在事件處理函數(shù)里的,即使可以這么做。事件處理函數(shù)應(yīng)該專注于處理事件,我們應(yīng)該讓它變得純粹。在 vue 中, 允許我們自定義過濾器(filters),可被用于一些常見的文本格式化。
過濾器可以用在兩個地方:雙花括號插值和 v-bind 表達(dá)式 (后者從 2.1.0+ 開始支持)。過濾器應(yīng)該被添加在 JavaScript 表達(dá)式的尾部,由 | 符號指示,我們看看怎么用:
<template><div class='hello'><h1>{{ message.split('').reverse().join('') }}</h1><!-- add this --><h1>{{ message | reverseString }}</h1></div> </template><script> export default {name: 'HelloWorld',data() {return {message: 'Welcome to Your Vue.js App',};},// add this filters: {reverseString(val) {let value = val;if (!value) return '';value = value.split('').reverse().join('');return value;},}, }; </script>代碼增多了,但是整體的語義化卻更好。從 filters 的用法我們可以看出:
- 它是一對一的,對單個數(shù)據(jù)進(jìn)行過濾,可以進(jìn)行傳參
- 適用于同方法、不同參數(shù)的情況
所以,filters 的缺點就很明顯了:如果要計算結(jié)合多個數(shù)據(jù)不同變化的情況,過濾器就無法適用了。這就要用到我們下面提到的計算屬性了。
二、計算屬性
在 vue 中,也為我們提供了computed 這個選項來處理數(shù)據(jù),我們稱它為計算屬性。當(dāng)邏輯復(fù)雜的時候,我們就應(yīng)當(dāng)使用 computed 計算屬性了。計算屬性使用起來非常簡單,我們還是用上面的例子,使用計算屬性來修改模板中的邏輯:
<template><div class='hello'><h1>{{ message.split('').reverse().join('') }}</h1><h1>{{ message | reverseString }}</h1><h1>{{ this.reversedMessageMethod() }}</h1><!-- add this --><h1>{{ reversedMessage }}</h1></div> </template><script> export default {name: 'HelloWorld',data() {return {message: 'Welcome to Your Vue.js App',};},filters: {reverseString(val) {let value = val;if (!value) return '';value = value.split('').reverse().join('');return value;},},// add thiscomputed: {reversedMessage() {return this.message.split('').reverse().join('');},},methods: {reversedMessageMethod() {return this.message.split('').reverse().join('');},}, }; </script>和 method 選項的使用非常相似。我們可以像綁定普通屬性一樣在模板中綁定計算屬性。
這兩種方式的最終結(jié)果確實是完全相同的。然而,不同的是:計算屬性是基于它們的依賴進(jìn)行緩存的。什么意思呢?
只在相關(guān)依賴發(fā)生改變時它們才會重新求值。這就意味著只要 message 還沒有發(fā)生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結(jié)果,而不必再次執(zhí)行函數(shù);而當(dāng)數(shù)據(jù)有變化時,只要有一個數(shù)據(jù)發(fā)生變化,則會重新計算,來更新視圖的改變。相比之下,每當(dāng)觸發(fā)重新渲染時,調(diào)用 methods 中的方法將總會再次執(zhí)行函數(shù)。
我們?yōu)槭裁葱枰彺?#xff1f;假設(shè)我們有一個性能開銷比較大的計算屬性 A,它需要遍歷一個巨大的數(shù)組并做大量的計算。然后我們可能有其他的計算屬性依賴于 A 。如果沒有緩存,我們將不可避免的多次執(zhí)行 A 的 getter!我們來看看計算屬性的具體應(yīng)用場景:
1、微博發(fā)文
發(fā)微博的時候,有字?jǐn)?shù)限制。在我們輸入文字的時候,輸入框會計算我們還可以輸入多少字:
<template><div><textarea v-model='content' :maxlength='totalcount'></textarea><p>你還可以輸入{{reduceCount}}字</p></div> </template><script> export default {data() {return {totalcount: 200, // 總共只給輸入200字content: '',};},computed: {reduceCount() {return this.totalcount - this.content.length;},}, }; </script>通過一直監(jiān)聽輸入的字符的長度來觸發(fā) computed 里的 reduceCount 方法,重新計算,然后返回給視圖,讓視圖作出相應(yīng)的變化。接下來我們再看一個例子。
2、足球比賽
這個例子是一個足球比賽的結(jié)果播報板,我們先看看最終的效果,再看代碼:
效果 :
代碼:
<template><div><h1>比賽時間:{{time}}s</h1><h2>直播播報:{{result}}</h2><div class='team'><div><p>中國隊進(jìn)球數(shù):{{team.china}}</p><button @click='team.china++'>點擊中國隊進(jìn)一球</button></div><div><p>韓國隊進(jìn)球數(shù):{{team.korea}}</p><button @click='team.korea++'>點擊韓國隊進(jìn)一球</button></div></div></div> </template><script> export default {created() {const time = setInterval(() => {this.time = this.time + 1;if (this.time === 90) {clearInterval(time);}}, 1000);},data() {return {time: 0,team: {china: 0,korea: 0,},};},computed: {result() {if (this.time < 90) {if (this.team.china > this.team.korea) {return '中國隊領(lǐng)先';} else if (this.team.china < this.team.korea) {return '韓國隊領(lǐng)先';}return '雙方僵持';}if (this.team.china > this.team.korea) {return '中國隊贏';} else if (this.team.china < this.team.korea) {return '韓國隊贏';}return '平局';},}, }; </script><style scoped> .team {display: flex;justify-content: center; } button {padding: 15px 60px;outline: none;background-color: #27ae60;display: block;font-size: 1rem;color: #fff;margin: 10px; } </style>通過上面的例子,我們就可以很清楚 computed 的作用了:觀察一個或者多個數(shù)據(jù),只要依賴的數(shù)據(jù)發(fā)生變化的時,這個函數(shù)就會重新計算。這樣我們就可以通過觀察所有數(shù)據(jù)來維護(hù)一個狀態(tài),也就是所謂的返回一個狀態(tài)值。
三、偵聽器
雖然計算屬性在大多數(shù)情況下更合適,但有時也需要一個自定義的偵聽器。vue 通過 watch 選項提供了一個更通用的方法,來響應(yīng)數(shù)據(jù)的變化。
computed 和 watch 都可以做同一件事,兩個選項都是對數(shù)據(jù)進(jìn)行時時監(jiān)聽。但是它們也有不同:
- computed 對多數(shù)據(jù)變動進(jìn)行監(jiān)聽,返回一個狀態(tài),維護(hù)一個狀態(tài)
- watch 是對一個數(shù)據(jù)監(jiān)聽,在數(shù)據(jù)變化時,會返回兩個值,一個是 value (當(dāng)前值),二是 oldvalue 是變化前的值
我們也可以用 watch 選項來改造上面的足球比賽的例子,添加一個 watch 選項:
<script> export default {created() {const time = setInterval(() => {this.time = this.time + 1;if (this.time === 90) {clearInterval(time);}}, 1000);},data() {return {time: 0,team: {china: 0,korea: 0,},};},// add this watch: {time(value, oldval) { // eslint-disable-lineif (value < 90) {if (this.team.china > this.team.korea) {this.result = '中國隊領(lǐng)先';} else if (this.team.china < this.team.korea) {this.result = '韓國隊領(lǐng)先';} else {this.result = '雙方僵持';}} else if (this.team.china > this.team.korea) {this.result = '中國隊贏';} else if (this.team.china < this.team.korea) {this.result = '韓國隊贏';} else {this.result = '平局';}},team(value, oldval) { // eslint-disable-lineif (this.time < 90) {if (value.china > value.korea) {this.result = '中國隊領(lǐng)先';} else if (value.china < value.korea) {this.result = '韓國隊領(lǐng)先';} else {this.result = '雙方僵持';}} else if (value.china > value.korea) {this.result = '中國隊贏';} else if (value.china < value.korea) {this.result = '韓國隊贏';} else {this.result = '平局';}},}, }; </script>可以看出跟使用 computed 選項是差不多一致的。那 watch 有什么應(yīng)用場景呢?
有一個很常見的場景:圖片的預(yù)加載。當(dāng)圖片數(shù)量比較大的時候,為了保證頁面圖片都加載出來的時候,才把主頁面給顯示出來,然后再進(jìn)行一些 ajax 請求,或者邏輯操作,這個時候用 computed 就無法實現(xiàn)了,只能用 watch ,看看代碼:
<template><div v-show='show'><img src='https://img.alicdn.com/simba/img/TB14sYVQXXXXXc1XXXXSutbFXXX.jpg' alt><img src='//img.alicdn.com/tfs/TB1iZ6EQXXXXXcsXFXXXXXXXXXX-520-280.jpg_q90_.webp' alt><img src='https://img.alicdn.com/simba/img/TB1C0dOPXXXXXarapXXSutbFXXX.jpg' alt><img src='//img.alicdn.com/tfs/TB1iZ6EQXXXXXcsXFXXXXXXXXXX-520-280.jpg_q90_.webp' alt></div> </template><script> export default {data() {return {count: 0,show: false,};},mounted() {const imgs = document.querySelectorAll('img');console.log(imgs); // eslint-disable-lineArray.from(imgs).forEach((item) => {const img = new Image();img.onload = () => {this.count = this.count + 1;};img.src = item.getAttribute('src');});},watch: {count(val, oldval) { // eslint-disable-lineif (val === 4) {this.show = true;alert('加載完畢'); // eslint-disable-line// 然后可以對后臺發(fā)送一些ajax操作}},}, }; </script>我們可以發(fā)現(xiàn)等四張圖片都加載完畢的時候頁面才顯示出來。所以當(dāng)我們想要在數(shù)據(jù)變化響應(yīng)時,執(zhí)行異步操作或開銷較大的操作,就需要使用 watch 了。
四、總結(jié)
過濾器 filter :
- 一對一,對單個數(shù)據(jù)進(jìn)行過濾,可以進(jìn)行傳參
- 適用于同方法、不同參數(shù)的情況
- 不適用于結(jié)合多個數(shù)據(jù)變化的情況
計算屬性 computed :
- 監(jiān)聽一個或者多個數(shù)據(jù)來維護(hù)返回一個狀態(tài)值
- 只在相關(guān)依賴發(fā)生改變時它們才會重新求值
偵聽器 watch :
- 對一個數(shù)據(jù)監(jiān)聽
- 在數(shù)據(jù)變化時,會返回兩個值,一個是 value (當(dāng)前值),二是 oldvalue 是變化前的值
本節(jié)內(nèi)容代碼:https://github.com/IDeepspace...
歡迎關(guān)注我的博客:https://togoblog.cn/總結(jié)
以上是生活随笔為你收集整理的Vue 计算属性与侦听器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: izoak028
- 下一篇: 移动端 | Vue.js对比微信小程序基