Vue?中的?computed?和?watch?的區(qū)別詳解
computed
computed 看上去是方法,但是實際上是計算屬性,它會根據(jù)你所依賴的數(shù)據(jù)動態(tài)顯示新的計算結(jié)果。計算結(jié)果會被緩存,computed 的值在 getter 執(zhí)行后是會緩存的,只有在它依賴的屬性值改變之后,下一次獲取 computed 的值時才會重新調(diào)用對應的 getter 來計算。
1)下面是一個比較經(jīng)典簡單的案例
<template>
<div class="hello">
{{fullName}}
</div>
</template>
<script>
export default {
data() {
return {
firstName: '飛',
lastName: "旋"
}
},
props: {
msg: String
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
</script>注意
在 Vue 的 template 模板內(nèi)({{}})是可以寫一些簡單的js表達式的很便利,如上直接計算 {{this.firstName + ' ' + this.lastName}},因為在模版中放入太多聲明式的邏輯會讓模板本身過重,尤其當在頁面中使用大量復雜的邏輯表達式處理數(shù)據(jù)時,會對頁面的可維護性造成很大的影響,而 computed 的設計初衷也正是用于解決此類問題。
應用場景
適用于重新計算比較費時不用重復數(shù)據(jù)計算的環(huán)境。所有 getter 和 setter 的 this 上下文自動地綁定為 Vue 實例。如果一個數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個數(shù)據(jù)設計為 computed
watch
watcher 更像是一個 data 的數(shù)據(jù)監(jiān)聽回調(diào),當依賴的 data 的數(shù)據(jù)變化,執(zhí)行回調(diào),在方法中會傳入 newVal 和 oldVal。可以提供輸入值無效,提供中間值 特場景。Vue 實例將會在實例化時調(diào)用 $watch(),遍歷 watch 對象的每一個屬性。如果你需要在某個數(shù)據(jù)變化時做一些事情,使用watch。
<template>
<div class="hello">
{{fullName}}
<button @click="setNameFun">click</button>
</div>
</template>
<script>
export default {
data() {
return {
firstName: '飛',
lastName: "旋"
}
},
props: {
msg: String
},
methods: {
setNameFun() {
this.firstName = "大";
this.lastName = "熊"
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
},
watch: {
firstName(newval,oldval) {
console.log(newval)
console.log(oldval)
}
}
}
</script>總結(jié)
- 1.如果一個數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個數(shù)據(jù)設計為 computed
- 2.如果你需要在某個數(shù)據(jù)變化時做一些事情,使用 watch 來觀察這個數(shù)據(jù)變化
到此這篇關于Vue 中的 computed 和 watch 的區(qū)別詳解的文章就介紹到這了,更多相關Vue computed 和 watch 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue項目中企業(yè)微信使用js-sdk時config和agentConfig配置方式詳解
這篇文章主要介紹了vue項目中企業(yè)微信使用js-sdk時config和agentConfig配置,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
Element-Ui組件 NavMenu 導航菜單的具體使用
這篇文章主要介紹了Element-Ui組件 NavMenu 導航菜單的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10

