語法
是什么?
直接上demo,了解一下語法先~
<template>
<div>
<p>num1為{{ num1 }}</p>
<p>num2為{{ num2 }}</p>
<p>num1+num2={{ result }}</p>
<button @click="incrementNum1">num1+1</button>
<button @click="incrementNum2">num2+2</button>
</div>
</template>
<script>
export default {
data() {
return {
num1: 1,
num2: 2
};
},
// computed對(duì)象里面的值,能夠根據(jù)其依賴發(fā)生的變化而變化,形象說,它是y,x發(fā)生變化,y自動(dòng)發(fā)生變化
computed: {
result() {
return this.num1 + this.num2;
}
},
// watch
watch: {
num1(newValue, oldValue) {
console.log(`num1 changed from ${oldValue} to ${newValue}`);
},
num2(newValue, oldValue) {
console.log(`num2 changed from ${oldValue} to ${newValue}`);
},
result(newValue, oldValue) {
console.log(`result changed from ${oldValue} to ${newValue}`);
}
},
methods: {
incrementNum1() {
this.num1++;
},
incrementNum2() {
this.num2=this.num2+2;
}
}
};
</script>
<style>
button{
display: block;
margin-top: 20px;
}
</style>
相同點(diǎn)
conputed是計(jì)算屬性,watch是監(jiān)聽屬性,本質(zhì)上都是同一個(gè)watcher實(shí)例,它們都是通過響應(yīng)式系統(tǒng)與數(shù)據(jù),頁面建立通信。
不同點(diǎn)
-
computed帶有"懶計(jì)算"功能
-
監(jiān)聽的邏輯有差異:computed是依賴的值變了,它去重新求值,watch是目標(biāo)值變了,它去執(zhí)行函數(shù)文章來源:http://www.zghlxwxcb.cn/news/detail-799872.html
-
深層到代碼:在數(shù)據(jù)更新時(shí), 計(jì)算屬性的dirty狀態(tài)會(huì)立即改變, 而監(jiān)聽屬性與組件重新渲染, 至少都會(huì)在下一個(gè)"tick"執(zhí)行,故監(jiān)聽屬性是異步觸發(fā)的文章來源地址http://www.zghlxwxcb.cn/news/detail-799872.html
到了這里,關(guān)于淺談Vue的屬性,computed和watch的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!