前言
- 作用:将一个响应式对象中的每一个属性,转换为ref对象
- 备注:toRefs与toRef功能一致,但toRefs可以批量转换
使用方式
<template>
<div class="person">
<h2>姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}},{{nl}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {reactive,toRefs,toRef} from 'vue'
// 数据
let person = reactive({
name:'喜爱',
age:18,
})
// let{name,age}=person // 此时解构出来的name和age不是响应式的
let {name,age} = toRefs(person) //toRefs接受由reactive定义的响应式对象,并把响应式里的每一组数据拎出来形成新的对象
let nl = toRef(person,'age')
console.log(nl,nl.value)
// 方法
function changeName(){
name.value += '~'
}
function changeAge(){
age.value += 1
}
</script>
<style scoped>
.person{
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
总结
可以参考:https://blog.csdn.net/cookcyq__/article/details/121618833