欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺析Vue3中的計算屬性和屬性監(jiān)聽

 更新時間:2023年08月24日 10:24:45   作者:Python?User  
這篇文章主要為大家詳細介紹了Vue3中的計算屬性和屬性監(jiān)聽的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下

compute計算屬性

Vue3中可以通過 compute進行監(jiān)聽計算屬性,他返回的是一個ref的對象,也就是說 通過compuye這種方式計算屬性實際上是進行了ref的操作

import { computed } from 'vue
const user = reactive({
    firstName: 'A',
    lastName: 'B'
})
// 只有getter的計算屬性
// 監(jiān)聽計算fullName1屬性
const fullName1 = computed(() => {
    console.log('fullName1')
    return user.firstName + '-' + user.lastName
})
// 有getter與setter的計算屬性
// 監(jiān)聽計算fullName2屬性
const fullName2 = computed({
    get () {
        console.log('fullName2 get')
        return user.firstName + '-' + user.lastName
    },
    set (value: string) {
        console.log('fullName2 set')
        const names = value.split('-')
        user.firstName = names[0]
        user.lastName = names[1]
     }
})
return {
    fullName1,
    fullName2,
}

watch 屬性監(jiān)聽

監(jiān)視指定的一個或多個響應式數(shù)據(jù), 一旦數(shù)據(jù)變化, 就自動執(zhí)行監(jiān)視回調(diào);

默認初始時不執(zhí)行回調(diào), 但可以通過配置immediate為true, 來指定初始時立即執(zhí)行第一次;

通過配置deep為true, 來指定深度監(jiān)視

import { watch } from 'vue
const user = reactive({
    firstName: 'A',
    lastName: 'B'
})
watch(user, () => {
    fullName3.value = user.firstName + '-' + user.lastName
}, {
    immediate: true,  // 是否初始化立即執(zhí)行一次, 默認是false
    deep: true, // 是否是深度監(jiān)視, 默認是false
})

其中 watch 也可以監(jiān)聽多個數(shù)據(jù)

/* 
watch多個數(shù)據(jù): 
    使用數(shù)組來指定
    如果是ref對象, 直接指定
    如果是reactive對象中的屬性,  必須通過函數(shù)來指定
*/
// ref 對象
watch([user.firstName, user.lastName, fullName3], (values) => {
    console.log('監(jiān)視多個數(shù)據(jù)', values)
})
// reactive 對象
watch([() => user.firstName, () => user.lastName, fullName3], (values) => {
    console.log('監(jiān)視多個數(shù)據(jù)', values)
})

watchEffect 屬性監(jiān)聽

不需要配置immediate,默認初始時就會執(zhí)行第一次, 從而可以收集需要監(jiān)視的數(shù)據(jù);

不用直接指定要監(jiān)視的數(shù)據(jù), 回調(diào)函數(shù)中使用的哪些響應式數(shù)據(jù)就監(jiān)視哪些響應式數(shù)據(jù)

import { watchEffect} from 'vue
const user = reactive({
    firstName: 'A',
    lastName: 'B'
})
// 監(jiān)視所有回調(diào)中使用的數(shù)據(jù)
watchEffect(() => {
    fullName3.value = user.firstName + '-' + user.lastName
}) 
return {
    user,
    fullName1,
    fullName2,
    fullName3
}

到此這篇關于淺析Vue3中的計算屬性和屬性監(jiān)聽的文章就介紹到這了,更多相關Vue3屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論