Vue中的watch用法

Vue中的watch用法


Vue.js中的watch主要用于觀察Vue實(shí)例上的數(shù)據(jù)變動(dòng)。

栗子:

<template>

? ? // 觀察數(shù)據(jù)為字符串或數(shù)組

? ? <input v-model="example0" />

? ? <input v-model="example1" />

? ? // 單觀察數(shù)據(jù)example2為對(duì)象時(shí),如果鍵值發(fā)生變化,為了監(jiān)聽到數(shù)據(jù)變化,需要添加deep:true參數(shù)

? ? <input v-model="example2.inner" />

</template>

<script>

? ? export default {

? ? ? ? data () {

? ? ? ? ? ? return {

? ? ? ? ? ? ? ? example0: "",

? ? ? ? ? ? ? ? example1: "",

? ? ? ? ? ? ? ? example2: {

? ? ? ? ? ? ? ? ? ? inner: 1

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? },

? ? ? ? watch: {

? ? ? ? ? ? example0 (curVal, oldVal) {

? ? ? ? ? ? ? ? console.log(curVal, oldVal)

? ? ? ? ? ? ?},

? ? ? ? ? ? example1: 'a',? // 值可以為methods的方法名

? ? ????????example2: {

????????????????//?注意:當(dāng)觀察的數(shù)據(jù)為對(duì)象或數(shù)組時(shí),curVal和oldVal是相等的,因?yàn)檫@兩個(gè)形參指向的是同一個(gè)數(shù)據(jù)對(duì)象

????????????????????handler (curVal, oldVal) {

????????????????????????console.log(curVal, oldVal)

????????????????????},

????????????????????deep: true

????????????????}

? ? ? ? },

????????methods: {

????????????????a: function (curVal, oldVal) {

????????????????????????console.log(curVal, oldVal)

????????????????}

????????}

? ? }

</script>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容