Computed properties and property listeners in Vue3

compute computed properties

In Vue3, you can listen to computed properties through compute, which returns a ref object, which means that computing properties through compuye is actually a ref operation

import {
    
     computed } from 'vue
const user = reactive({
    
    
	firstName: 'A',
    lastName: 'B'
})
// 只有getter的计算属性
// 监听计算fullName1属性
const fullName1 = computed(() => {
    
    
    console.log('fullName1')
    return user.firstName + '-' + user.lastName
})
// 有getter与setter的计算属性
// 监听计算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 property monitor

  • Monitor the specified one or more responsive data, once the data changes, the monitoring callback will be executed automatically;
  • By default, the callback is not executed at the initial stage, but you can configure immediate to be true to specify that the initial stage is executed immediately for the first time;
  • Specify deep monitoring by configuring deep as true
import {
    
     watch } from 'vue
const user = reactive({
    
    
	firstName: 'A',
    lastName: 'B'
})
watch(user, () => {
    
    
    fullName3.value = user.firstName + '-' + user.lastName
}, {
    
    
    immediate: true,  // 是否初始化立即执行一次, 默认是false
    deep: true, // 是否是深度监视, 默认是false
})

Among them, watch can also monitor multiple data

/* 
watch多个数据: 
    使用数组来指定
    如果是ref对象, 直接指定
    如果是reactive对象中的属性,  必须通过函数来指定
*/
// ref 对象
watch([user.firstName, user.lastName, fullName3], (values) => {
    
    
	console.log('监视多个数据', values)
})
// reactive 对象
watch([() => user.firstName, () => user.lastName, fullName3], (values) => {
    
    
	console.log('监视多个数据', values)
})

watchEffect attribute monitoring

  • There is no need to configure immediate, and it will be executed for the first time by default, so that the data that needs to be monitored can be collected;
  • Instead of directly specifying the data to be monitored, which responsive data is used in the callback function to monitor which responsive data
import {
    
     watchEffect} from 'vue
const user = reactive({
    
    
	firstName: 'A',
    lastName: 'B'
})
// 监视所有回调中使用的数据
watchEffect(() => {
    
    
    fullName3.value = user.firstName + '-' + user.lastName
}) 
return {
    
    
    user,
    fullName1,
    fullName2,
    fullName3
}

Guess you like

Origin blog.csdn.net/weixin_44684357/article/details/132433367