vue3_toRef的使用及特点

202 阅读1分钟

官方文档

可以用来为源响应式对象上的某个 property 新创建一个 ref。然后,ref 可以被传递,它会保持对其源 property 的响应式连接。

src\App.vue

<template>
    <h2>toRef的使用及特点:</h2>
    <h3>state:{{state}}</h3>
    <h3>age:{{age}}</h3>
    <h3>money:{{money}}</h3>
    <hr>
    <button @click="update">更新数据</button>

    <hr>
    <child :age='age'></child>
</template>

<script lang="ts">
import { defineComponent, reactive, toRef, ref } from 'vue'
import Child from './components/Child.vue'

export default defineComponent({
    components: { Child },
    setup() {
        const state = reactive({
            age: 5,
            money: 100,
        })

        // 把响应式数据state对象中的某个属性age变成了ref对象
        const age = toRef(state, 'age')
        const money = ref(state.money)
        console.log(age, money)

        const update = () => {
            // state,age一起修改
            state.age += 2
            // age.value += 3

            // 只修改money
            // money.value += 10
        }

        return {
            state,
            age,
            money,
            update,
        }
    },
})
</script>

src\components\Child.vue

<template>
    <h2>Child子集组件</h2>
    <h3>age:{{age}}</h3>
    <h3>length:{{length}}</h3>
</template>

<script lang="ts">
import { computed, defineComponent, Ref, toRef } from 'vue'

function useGetLength(age: Ref) {
    return computed(() => {
        return age.value.toString().length
    })
}

export default defineComponent({
    name: 'App',
    props: {
        age: {
            type: Number,
            required: true,
        },
    },
    setup(props) {
        const length = useGetLength(toRef(props, 'age'))
        return {
            length,
        }
    },
})
</script>