亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網(wǎng)為廣大站長提供免費收錄網(wǎng)站服務,提交前請做好本站友鏈:【 網(wǎng)站目錄:http://www.430618.com 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

這篇文章主要介紹了vue3 watchwatchEffect的使用以及有哪些區(qū)別,幫助大家更好的理解和學習vue框架,感興趣的朋友可以了解下

1、watch偵聽器

引入watch

import { ref, reactive, watch, toRefs } from 'vue'

對基本數(shù)據(jù)類型進行監(jiān)聽----- watch特性:

1、具有一定的惰性lazy 第一次頁面展示的時候不會執(zhí)行,只有數(shù)據(jù)變化的時候才會執(zhí)行

2、參數(shù)可以拿到當前值和原始值

3、可以偵聽多個數(shù)據(jù)的變化,用一個偵聽起承載

setup() {
    const name = ref('leilei')
    watch(name, (curVal, prevVal) => {
        console.log(curVal, prevVal)
    })
}
template: 'Name: <input v-model="name" />'

對引用類型進行監(jiān)聽-----

setup() {
    const nameObj = reactive({name: 'leilei', englishName: 'bob'})
    監(jiān)聽一個數(shù)據(jù)
    watch(() => nameObj.name, (curVal, prevVal) => {
        console.log(curVal, prevVal)
    })
    監(jiān)聽多個數(shù)據(jù) 
    watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => {
        console.log(curName, curEng, '----', prevName, curEng)
        setTimeout(() => {
            stop1()
        }, 5000)
    })
    const { name, englishName } = toRefs(nameObj)
}
template: 'Name: <input v-model="name" /> englishName: <input v-model="englishName" />'

2、watchEffect

沒有過多的參數(shù) 只有一個回調函數(shù)

1、立即執(zhí)行,沒有惰性,頁面的首次加載就會執(zhí)行。

2、自動檢測內部代碼,代碼中有依賴 便會執(zhí)行

3、不需要傳遞要偵聽的內容 會自動感知代碼依賴,不需要傳遞很多參數(shù),只要傳遞一個回調函數(shù)

4、不能獲取之前數(shù)據(jù)的值 只能獲取當前值

5、一些=異步的操作放在這里會更加合適

watchEffect(() => {
    console.log(nameObj.name) 
})

偵聽器的取消 watch 取消偵聽器用法相同

const stop = watchEffect(() => {
    console.log(nameObj.name) 
    setTimeout(() => {
        stop()
    }, 5000)
})
const stop1 = watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => {
    console.log(curName, curEng, '----', prevName, curEng)
    setTimeout(() => {
        stop1()
    }, 5000)
})

watch也可以變?yōu)榉嵌栊缘?立即執(zhí)行的 添加第三個參數(shù) immediate: true

watch([() => nameObj.name, () => nameObj.name], ([curName, curEng], [prevName, curEng]) => {
    console.log(curName, curEng, '----', prevName, curEng)
    setTimeout(() => {
        stop1()
    }, 5000)
}, {
    immediate: true
})



分享到:
標簽:vue3 watch watchEffect
用戶無頭像

網(wǎng)友整理

注冊時間:

網(wǎng)站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨大挑戰(zhàn)2018-06-03

數(shù)獨一種數(shù)學游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數(shù)有氧達人2018-06-03

記錄運動步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定