<!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处理的数据无论是原始数据,“包裹后的数据”,还是模板,都有变化。
对于toRef:
toRef处理的数据会有变化,而原始数据也有变化,但是模板没有变化
对于toRefs:wtoRefs处理的数据响应变化,原始数据也响应变化,但是模板并没有变化
总结
处理数据类型 | 处理后数据类型 | 原始数据变化 | 模板变化 | |
ref | 基础类型数据 | RefImpl对象类型(来自原数据的拷贝) | 无 | 有 |
reactive | 数组,对象 | Proxy (对原数据对象加一层代理),因此有同步变化 | 有(原始对象) | 有 |
toRef | 对象的属性 | ObjectRefImpl对象类型 | 有(原始对象) | 无 |
toRefs | 对象 | 多个ObjectRefImpl组成的对象 | 有(原始对象) | 无 |