龙空技术网

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

tchaihomjon 113

前言:

此刻同学们对“refhtml”大致比较珍视,我们都想要分析一些“refhtml”的相关知识。那么小编同时在网摘上网罗了一些对于“refhtml””的相关知识,希望我们能喜欢,你们快快来学习一下吧!

首先来一个用于测试的Demo页:

<!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=";></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处理的数据无论是原始数据,“包裹后的数据”,还是模板,都有变化。

对于toRef:

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

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

总结

标签: #refhtml