vue中watch和computed的區(qū)別詳解
今天給大家講一下watch跟computed的區(qū)別,下面我們直接開始吧
- 功能上:computed是計算屬性,watch是監(jiān)聽一個值的變化,然后執(zhí)行對應(yīng)的回調(diào)。
- 是否調(diào)用緩存:computed中的函數(shù)所依賴的屬性沒有發(fā)生變化,那么調(diào)用當(dāng)前的函數(shù)的時候會從緩存中讀取,而watch在每次監(jiān)聽的值發(fā)生變化的時候都會執(zhí)行回調(diào)。
- 是否調(diào)用return:computed中的函數(shù)必須要用return返回,watch中的函數(shù)不是必須要用return。
- computed默認(rèn)第一次加載的時候就開始監(jiān)聽;watch默認(rèn)第一次加載不做監(jiān)聽,如果需要第一次加載做監(jiān)聽,添加immediate屬性,設(shè)置為true(immediate:true)
- 使用場景:computed----當(dāng)一個屬性受多個屬性影響的時候,使用computed-----購物車商品結(jié)算。watch–當(dāng)一條數(shù)據(jù)影響多條數(shù)據(jù)的時候,使用watch-----搜索框.
watch的實現(xiàn)

<body>
<div id="app">
姓: <input type="text" v-model=firstName> 名:
<input type="text" v-model=lastName> 姓名:
<span>{{fullname}}</span>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
firstName: 'z',
lastName: 's',
fullname: 'zs'
},
watch: {
firstName(newval) {
?
this.fullname = newval + this.lastName
},
lastName(newval) {
this.fullname = this.firstName + newval
}
?
}
})
?
</script> computed的實現(xiàn)

<body>
<div id="app">
姓: <input type="text" v-model=firstName> 名:
<input type="text" v-model=lastName> 姓名:
<span>{{fullname}}</span>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
firstName: 'z',
lastName: 's'
},
computed: {
fullname() {
return this.firstName + this.lastName
}
}
})
?
</script> watch與computed區(qū)別總結(jié)
computed支持緩存,相依賴的數(shù)據(jù)發(fā)生改變才會重新計算;watch不支持緩存,只要監(jiān)聽的數(shù)據(jù)變化就會觸發(fā)相應(yīng)操作
computed不支持異步,當(dāng)computed內(nèi)有異步操作時是無法監(jiān)聽數(shù)據(jù)變化的;watch支持異步操作
computed屬性的屬性值是一函數(shù),函數(shù)返回值為屬性的屬性值,computed中每個屬性都可以設(shè)置set與get方法。watch監(jiān)聽的數(shù)據(jù)必須是data中聲明過或父組件傳遞過來的props中的數(shù)據(jù),當(dāng)數(shù)據(jù)變化時,觸發(fā)監(jiān)聽器
最后
到此這篇關(guān)于vue中watch跟computed的區(qū)別詳解的文章就介紹到這了,更多相關(guān)watch跟computed區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue實現(xiàn)側(cè)邊菜單欄手風(fēng)琴效果實例代碼
本文通過一段簡單的代碼給大家介紹了基于純vue實現(xiàn)側(cè)邊菜單欄手風(fēng)琴效果,代碼很簡單,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-05
Vue實現(xiàn)導(dǎo)航欄的顯示開關(guān)控制
今天小編就為大家分享一篇Vue實現(xiàn)導(dǎo)航欄的顯示開關(guān)控制,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
在Vue里如何把網(wǎng)頁的數(shù)據(jù)導(dǎo)出到Excel的方法
這篇文章主要介紹了在Vue里如何把網(wǎng)頁的數(shù)據(jù)導(dǎo)出到Excel,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
探索Vue.js component內(nèi)容實現(xiàn)
這篇文章主要和大家一起探索Vue.js component內(nèi)容實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11

