溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue中watch怎么使用

發(fā)布時(shí)間:2022-11-07 09:58:00 來(lái)源:億速云 閱讀:121 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了Vue中watch怎么使用的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Vue中watch怎么使用文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

一、API介紹

watch(WatcherSource, Callback, [WatchOptions])

type WatcherSource<T> = Ref<T> | (() => T)

interface WatchOptions extends WatchEffectOptions {
    deep?: boolean // 默認(rèn):false
  immediate?: boolean // 默認(rèn):false
  
}

參數(shù)說(shuō)明:

WatcherSource: 用于指定要偵聽(tīng)的響應(yīng)式變量。WatcherSource可傳入ref響應(yīng)式數(shù)據(jù),reactive響應(yīng)式對(duì)象要寫(xiě)成函數(shù)的形式。

Callback: 執(zhí)行的回調(diào)函數(shù),可依次接收當(dāng)前值newValue,先前值oldValue作為入?yún)ⅰ?/p>

WatchOptions:支持 deep、immediate。當(dāng)需要對(duì)響應(yīng)式對(duì)象進(jìn)行深度監(jiān)聽(tīng)時(shí),設(shè)置deep: true;默認(rèn)情況下watch是惰性的,當(dāng)我們?cè)O(shè)置immediate: true時(shí),watch會(huì)在初始化時(shí)立即執(zhí)行回調(diào)函數(shù)。

除此之外,vue3的watch還支持偵聽(tīng)多個(gè)響應(yīng)式數(shù)據(jù),也能手動(dòng)停止watch監(jiān)聽(tīng)。

二、監(jiān)聽(tīng)多個(gè)數(shù)據(jù)源

<template>
  <div class="watch-test">
    <div>name:{{name}}</div>
    <div>age:{{age}}</div>
  </div>
  <div>
    <button @click="changeName">改變名字</button>
    <button @click="changeAge">改變年齡</button>
  </div>
</template>

<script>
  import {ref, watch} from 'vue'

  export default {
    name: 'Home',
    setup() {

      const name = ref('小松菜奈')
      const age = ref(25)

      const watchFunc = watch([name, age], ([name, age], [prevName, prevAge]) => {
        console.log('newName', name, 'oldName', prevName)
        console.log('newAge', age, 'oldAge', prevAge)
        if (age > 26) {
          watchFunc() // 停止監(jiān)聽(tīng)
        }
      },{immediate:true})

      const changeName = () => {
        name.value = '有村架純'
      }
      const changeAge = () => {
        age.value += 2
      }
      return {
        name,
        age,
        changeName,
        changeAge
      }
    }
  }
</script>

現(xiàn)象:當(dāng)改變名字和年齡時(shí),watch都監(jiān)聽(tīng)到了數(shù)據(jù)的變化。當(dāng)age大于26時(shí),我們停止了監(jiān)聽(tīng),此時(shí)再改變年齡,由于watch的停止,導(dǎo)致watch的回調(diào)函數(shù)失效。

結(jié)論:我們可以通過(guò)watch偵聽(tīng)多個(gè)值的變化,也可以利用給watch函數(shù)取名字,然后通過(guò)執(zhí)行名字()函數(shù)來(lái)停止偵聽(tīng)。

三、偵聽(tīng)數(shù)組

<template>
  <div class="watch-test">
    <div>ref定義數(shù)組:{{arrayRef}}</div>
    <div>reactive定義數(shù)組:{{arrayReactive}}</div>
  </div>
  <div>
    <button @click="changeArrayRef">改變r(jià)ef定義數(shù)組第一項(xiàng)</button>
    <button @click="changeArrayReactive">改變r(jià)eactive定義數(shù)組第一項(xiàng)</button>
  </div>
</template>

<script>
  import {ref, reactive, watch} from 'vue'

  export default {
    name: 'WatchTest',
    setup() {
      const arrayRef = ref([1, 2, 3, 4])
      const arrayReactive = reactive([1, 2, 3, 4])

      //ref not deep
      const arrayRefWatch = watch(arrayRef, (newValue, oldValue) => {
        console.log('newArrayRefWatch', newValue, 'oldArrayRefWatch', oldValue)
      })

      //ref deep
      const arrayRefDeepWatch = watch(arrayRef, (newValue, oldValue) => {
        console.log('newArrayRefDeepWatch', newValue, 'oldArrayRefDeepWatch', oldValue)
      }, {deep: true})

      //reactive,源不是函數(shù)
      const arrayReactiveWatch = watch(arrayReactive, (newValue, oldValue) => {
        console.log('newArrayReactiveWatch', newValue, 'oldArrayReactiveWatch', oldValue)
      })

      // 數(shù)組監(jiān)聽(tīng)的最佳實(shí)踐- reactive且源采用函數(shù)式返回,返回拷貝后的數(shù)據(jù)
      const arrayReactiveFuncWatch = watch(() => [...arrayReactive], (newValue, oldValue) => {
        console.log('newArrayReactiveFuncWatch', newValue, 'oldArrayReactiveFuncWatch', oldValue)
      })

      const changeArrayRef = () => {
        arrayRef.value[0] = 6
      }
      const changeArrayReactive = () => {
        arrayReactive[0] = 6
      }
      return {
        arrayRef,
        arrayReactive,
        changeArrayRef,
        changeArrayReactive
      }
    }
  }
</script>

現(xiàn)象:當(dāng)將數(shù)組定義為響應(yīng)式數(shù)據(jù)ref時(shí),如果不加上deep:true,watch是監(jiān)聽(tīng)不到值的變化的;而加上deep:true,watch可以檢測(cè)到數(shù)據(jù)的變化,但老值和新值一樣,即不能獲取老值。當(dāng)數(shù)組定義為響應(yīng)式對(duì)象時(shí),不作任何處理,watch可以檢測(cè)到數(shù)據(jù)的變化,但老值和新值一樣;如果把watch的數(shù)據(jù)源寫(xiě)成函數(shù)的形式并通過(guò)擴(kuò)展運(yùn)算符克隆一份數(shù)組返回,就可以在監(jiān)聽(tīng)的同時(shí)獲得新值和老值。

結(jié)論:定義數(shù)組時(shí),最好把數(shù)據(jù)定義成響應(yīng)式對(duì)象reactive,這樣watch監(jiān)聽(tīng)時(shí),只需要把數(shù)據(jù)源寫(xiě)成函數(shù)的形式并通過(guò)擴(kuò)展運(yùn)算符克隆一份數(shù)組返回,即可在監(jiān)聽(tīng)的同時(shí)獲得新值和老值。

四、偵聽(tīng)對(duì)象

<template>
  <div class="watch-test">
    <div>user:{</div>
      <div>name:{{objReactive.user.name}}</div>
      <div>age:{{objReactive.user.age}}</div>
    <div>}</div>
    <div>brand:{{objReactive.brand}}</div>
    <div>
      <button @click="changeAge">改變年齡</button>
    </div>
  </div>
</template>

<script>
  import {ref, reactive, watch} from 'vue'
  import _ from 'lodash';

  export default {
    name: 'WatchTest',
    setup() {
      const objReactive = reactive({user: {name: '小松菜奈', age: '20'}, brand: 'Channel'})

      //reactive 源是函數(shù)
      const objReactiveWatch = watch(() => objReactive, (newValue, oldValue) => {
        console.log('objReactiveWatch')
        console.log('new:',JSON.stringify(newValue))
        console.log('old:',JSON.stringify(oldValue))
      })

      //reactive,源是函數(shù),deep:true
      const objReactiveDeepWatch = watch(() => objReactive, (newValue, oldValue) => {
        console.log('objReactiveDeepWatch')
        console.log('new:',JSON.stringify(newValue))
        console.log('old:',JSON.stringify(oldValue))
      }, {deep: true})

      // 對(duì)象深度監(jiān)聽(tīng)的最佳實(shí)踐- reactive且源采用函數(shù)式返回,返回深拷貝后的數(shù)據(jù)
      const objReactiveCloneDeepWatch = watch(() => _.cloneDeep(objReactive), (newValue, oldValue) => {
        console.log('objReactiveCloneDeepWatch')
        console.log('new:',JSON.stringify(newValue))
        console.log('old:',JSON.stringify(oldValue))
      })

      const changeAge = () => {
        objReactive.user.age = 26
      }

      return {
        objReactive,
        changeAge
      }
    }
  }
</script>

現(xiàn)象:當(dāng)把對(duì)象定義為響應(yīng)式對(duì)象reactive時(shí),采用函數(shù)形式的返回,如果不加上deep:true,watch是監(jiān)聽(tīng)不到值的變化的;而加上deep:true,watch可以檢測(cè)到數(shù)據(jù)的變化,但老值和新值一樣,即不能獲取老值;若把watch的數(shù)據(jù)源寫(xiě)成函數(shù)的形式并通過(guò)深拷貝克隆(這里用了lodash庫(kù)的深拷貝)一份對(duì)象返回,就可以在監(jiān)聽(tīng)的同時(shí)獲得新值和老值。

結(jié)論:定義對(duì)象時(shí),最好把數(shù)據(jù)定義成響應(yīng)式對(duì)象reactive,這樣watch監(jiān)聽(tīng)時(shí),只需要把數(shù)據(jù)源寫(xiě)成函數(shù)的形式并通過(guò)深拷貝克隆一份對(duì)象返回,即可在監(jiān)聽(tīng)的同時(shí)獲得新值和老值。

vue是什么

Vue是一套用于構(gòu)建用戶界面的漸進(jìn)式JavaScript框架,Vue與其它大型框架的區(qū)別是,使用Vue可以自底向上逐層應(yīng)用,其核心庫(kù)只關(guān)注視圖層,方便與第三方庫(kù)和項(xiàng)目整合,且使用Vue可以采用單文件組件和Vue生態(tài)系統(tǒng)支持的庫(kù)開(kāi)發(fā)復(fù)雜的單頁(yè)應(yīng)用。

關(guān)于“Vue中watch怎么使用”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Vue中watch怎么使用”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI