methods,computed,watch三者區(qū)別?【專(zhuān)欄11】

watch
當(dāng)數(shù)據(jù)改變時(shí),直接觸發(fā)對(duì)應(yīng)操作; 可以監(jiān)聽(tīng)的數(shù)據(jù)有三部分,即props,data,computed; 所觸發(fā)的對(duì)應(yīng)操作函數(shù)中包含兩個(gè)參數(shù),第一個(gè)參數(shù)是新值newValue,第二個(gè)參數(shù)是舊值oldValue; 不支持緩存,但支持異步,在數(shù)據(jù)變化時(shí)執(zhí)行異步或開(kāi)銷(xiāo)較大的操作時(shí)使用; 一對(duì)多,即一個(gè)數(shù)據(jù)改變時(shí),可以通過(guò)觸發(fā)對(duì)應(yīng)操作改變多個(gè)其他的數(shù)據(jù)。
computed
computed 依賴(lài)于 data 中的數(shù)據(jù),只要在它的相關(guān)依賴(lài)發(fā)生改變時(shí)就會(huì)觸發(fā)computed; 計(jì)算屬性是基于屬性的依賴(lài)進(jìn)行緩存的,當(dāng)data中的數(shù)據(jù)未變時(shí),優(yōu)先取緩存中的東西; 支持緩存,但不支持異步; 多對(duì)一或一對(duì)一,即一個(gè)屬性是由其他屬性計(jì)算而來(lái)的,這個(gè)屬性可能是依賴(lài)其他一個(gè)或多個(gè)屬性。
methods
是一個(gè)方法,執(zhí)行的時(shí)候需要事件進(jìn)行觸發(fā); 可以在模板或者js中以方法的形式調(diào)用 執(zhí)行次數(shù)跟調(diào)用次數(shù)想對(duì)應(yīng)
使用說(shuō)明
export default {
data: {
userName: '鬼鬼'
},
watch:{
userName(newValue,oldValue){
console.log(`原來(lái)的值:${newValue}`);
console.log(`新的值${oldValue}`);
},
//深度監(jiān)聽(tīng)
userName:{
handler:function(newValue,oldValue){
console.log(`原來(lái)的值:${newValue}`);
console.log(`新的值${oldValue}`);
},
immediate:true,
deep:true
},
},
computed: {
gUserName() {
return this.userName
},
//computed傳參
gUserName(keyName){
return function(keyName){
return keyName+this.userName
}
}
},
methods: {
getUserName() {
return this.userName
}
}
}
<template>
<!-- methods -->
<div> 我的名字叫:{{ getUserName() }} </div>
<!-- computed -->
<div> 我的名字叫:{{ gUserName }} </div>
<!-- computed 傳參 -->
<div> {{ gUserName("我的名字叫:") }} </div>
</template>
說(shuō)明
本專(zhuān)欄總共匯總了
150道題,每道題目答案沒(méi)有多余扯皮的部分,就是單純的答案。關(guān)注公眾號(hào),每天一到面試題,為下次跳槽準(zhǔn)備,人人都能沖擊
30k+,點(diǎn)擊↓關(guān)注【鬼哥】當(dāng)前進(jìn)度【#011題】,如果你能點(diǎn)贊分享、鬼哥騎自行車(chē)也是開(kāi)心的
評(píng)論
圖片
表情
