chaihongjun.me

vue3中ref,reactive,toRef,toRefs的区别

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ref active toRef toRefs</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.1.1/vue.global.js"></script>
</head>

<body>
    <div id="app">
        <span> ref: </span>
        <input type="text" v-model="refValue" @input="inputRefHander" />
        {{ refValue }}
        <hr>
        <span> reactive: (显示age的值)</span>
        <input type="text" v-model="reactiveValue.age" @input="inputReactiveHander"  />
        {{ reactiveValue.age }}
        <hr>
        <span> toRef: (使age有响应)</span>
        <input type="text" v-model="toRefValue" @input="inputToRefValueHander" />
        {{ toRefValue}}
        <hr>
        <span> toRefs: </span>
        <input type="text" v-model="toRefsValue.name.value" @input="inputToRefsValueHander" />
        {{ toRefsValue.name.value}}
    </div>
</body>

</html>
<script>
const { createApp, reactive, toRefs, ref, toRef } = Vue;
const app = createApp({
    setup() {
        let name = 'chj';
        const obj = { name: 'chj', gender: 'male', age: 18 }

        const refValue = ref(name);               // => reactive({value:'chj'})
        const reactiveValue = reactive(obj)       // => reactive({ name: 'chj', gender: 'male', age: 18 })
        const toRefValue = toRef(obj, 'age')      // => reactive({value:18})
        const toRefsValue = toRefs(obj)           

        function inputRefHander() {
            console.log(`ref:::refValue:`);
            console.log(refValue);
            console.log(`原始数据`);
            console.log(name);
        }

        function inputReactiveHander() {
            console.log(`reactive:::reactiveValue`);
            console.log(reactiveValue);
            console.log(`原始数据`);
            console.log(obj);
        }

        function inputToRefValueHander() {
            console.log(`toRef:::toRefValue: `);
            console.log(toRefValue);
            console.log(`原始数据:`);
            console.log(obj);
        }

        function inputToRefsValueHander() {
            console.log(`toRefs:::toRefsValue: `);
            console.log(toRefsValue);
            console.log(`原始数据:`);
            console.log(obj);
        }
        return { refValue, inputRefHander, reactiveValue, inputReactiveHander, toRefValue, inputToRefValueHander, toRefsValue, inputToRefsValueHander }
    }
})
app.mount("#app")
</script>

随意输入内容,发现ref“包裹的”数据变化如下:

对于ref:

 原始数据没有变化,而ref“包裹的数据”变成了一个新的对象,而且模板有变化。


对于reactive:

reactive处理的数据无论是原始数据,“包裹后的数据”,还是模板,都有变化。


5.png

对于toRef:

toRef处理的数据会有变化,而原始数据也有变化,但是模板没有变化


对于toRefs:wtoRefs处理的数据响应变化,原始数据也响应变化,但是模板并没有变化

总结


处理数据类型处理后数据类型原始数据变化模板变化
ref基础类型数据RefImpl对象类型(来自原数据的拷贝)
reactive数组,对象Proxy (对原数据对象加一层代理),因此有同步变化有(原始对象)
toRef对象的属性ObjectRefImpl对象类型有(原始对象)
toRefs对象多个ObjectRefImpl组成的对象有(原始对象)


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:chaihongjun»