【vue3】computed、watch和watchEffect

1. computed

  • 只有一个回调函数,表示 get 方法
  • get 和 set 方法
<template>
    <fieldset>
        <legend>输入</legend>
        <input type="text" placeholder="输入名字" v-model="user.firstName">
        <input type="text" placeholder="输入名字" v-model="user.lastName">
    </fieldset>
    <fieldset>
        <legend>回显</legend>
        <input type="text" placeholder="显示名字" v-model="fullName1">
        <input type="text" placeholder="显示名字" v-model="fullName2">
    </fieldset>
</template>

<script lang="ts">
import { reactive, computed, ref } from 'vue'

export default {
    setup(props) {
        const user = reactive({
            firstName:'东方',
            lastName:'不败'
        })
        // 只有一个回调函数,表示 get 方法
        const fullName1 = computed(() => {
            return user.firstName + user.lastName
        })
        // get 和 set 方法
        const fullName2 = computed({
            get(){
                return user.firstName + '_' + user.lastName
            },
            set(val){
                console.log(val);
                const names = val.split('_')
                user.firstName = names[0]
                user.lastName = names[1]
            }
        })
        return { 
            user,
            fullName1,
            fullName2
        }
    }
}
</script>

2. watch和watchEffect

  • watchEffect 方法,不需要配置 immediate:true,默认会执行一次
  • watch 方法,可以监听多个数据,非响应式数据使用回调方式
<template>
    <fieldset>
        <legend>输入</legend>
        <input type="text" placeholder="输入名字" v-model="user.firstName">
        <input type="text" placeholder="输入名字" v-model="user.lastName">
    </fieldset>
    <fieldset>
        <legend>回显</legend>
        <input type="text" placeholder="显示名字" v-model="fullName3">
    </fieldset>
</template>

<script lang="ts">
import { reactive, ref, watchEffect, watch } from 'vue'

export default {
    setup(props) {
        const user = reactive({
            firstName:'东方',
            lastName:'不败'
        })
        // watchEffect 方法,不需要配置 immediate:true,默认会执行一次
        const fullName3 = ref('')
        watchEffect(() => {
            fullName3.value = user.firstName + user.lastName
        })
        // watch 方法
        // 可以监听多个数据,非响应式数据使用回调方式
        watch([()=>user.firstName,()=>user.lastName,fullName3], () => {
            console.log('111111111');
        })
        return { 
            user,
            fullName3
        }
    }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值