Vue中toRef与toRefs的区别
条件: vue setup
作用:toRef、toRefs用于将reactive内的节点提取出来,同时具有响应式结构。
一、toRef用法:
<script setup> import { reactive, toRef, toRefs } from 'vue' var student = reactive({ name: '张三', age: 15, contact: { phone: '18714896998', qq: '103422412', email: 'wm218@qq.com' } }) // 定义toRef var name = toRef(student, 'name') // toRef用法 var phone = toRef(student.contact, 'qq') // toRef用法
console.log(name.value); name.value = '李四' //修改toRef的值时,status会同步响应
console.log(student); // 打印修改后的结果
</script>
二、toRefs用法:
<template>
<view></view>
</template>
<script setup>
import {
reactive,
toRef,
toRefs
} from 'vue'
var student = reactive({
name: '张三',
age: 15,
contact: {
phone: '18714896998',
qq: '103422412',
email: 'wm218@qq.com'
}
})
// toRefs
var info = toRefs(student)
// 这种调用方式等同于直接调用student的结构
console.log(info.name.value); // 此时info结构:{name: ..., age: ..., contace: ...}
// 常用于组件、函数返回动态响应式变量
var getInfo = function(){
return {...toRefs(student)}
}
console.log(getInfo().name.value);
</script>
注意:
toRef与toRefs都是将reactive的json内节点提取出来,做为独立的响应式结构。
二者的区别在于:toRef是指定某一节点提取出来,toRefs是一次性将所有节点提取出来。但toRefs只能提取一级节点!
toRefs返回的变量修改,与原始值无任何响应式关联。
toRefs只提取第一级子节点示例:
<script setup> import { toRefs, reactive, } from 'vue' const c = reactive({ a:1, b: { c:1, e:2 } }) const k = toRefs(c) console.log(k.b.value); // 这里显示结果为: {} </script>
SO:它们 存在的意义:
有时需要将结构中的数据节点暴露给外部调用,这时得用toRef、toRefs。且暴露出去的数据也是响应式的,所以外部对该数据的变化也能同步到组件视图内。
下面案例中,直接通过父组件修改子组件内的变量:
组件test.vue代码:
<template>
<view>姓名:{{student.name}}</view>
<view>年龄:{{student.age}}</view>
<view>手机:{{student.contact.phone}}</view>
<view>企鹅:{{student.contact.qq}}</view>
<view>邮箱:{{student.contact.email}}</view>
<view>学生数量:{{studentNumber}}</view>
</template>
<script setup>
import {
ref,
reactive,
toRefs
} from 'vue'
var student = reactive({
name: '张三',
age: 15,
contact: {
phone: '18714896998',
qq: '103422412',
email: 'wm218@qq.com'
}
})
var studentNumber = ref(20)
defineExpose({
// ...student, 如果采用这种方式展开,暴露出的数据将不会同步
...toRefs(student), // 必需要通过toRefs数据才能同步
studentNumber // 这里的数据可以同步
})
</script>
父组件修改数据,子组件同步响应示例:
<template>
<test ref="student"></test>
</template>
<script setup>
import {
ref,
toRef,
toRefs,
reactive,
onMounted
} from 'vue'
// 获取组件实例,必需在setup内才能获取
let student = ref(null);
var info
// 获取组件值,必需要挂载完成之后才能获取
onMounted(() => {
// 延迟5秒查看变化
setTimeout(() => {
// 这里有二个细节:
// 1. 获取组件对外暴露接口,采用 student._value 方式
// 2. 必需定义成动态响应式的(toRefs或toRef转换),否则暴露的数据为只读
// info = reactive({...student._value}) 这种方式也不行
info = {
...toRefs(student._value) //将组件值扩展开,并是响应式的
}
info.studentNumber.value = 50 // 修改此处,将会同步更新到组件
info.name.value = '李四' // 修改此处,将会同步更新到组件
}, 5000)
});
</script>

浙公网安备 33010602011771号