toRef / toRefs
作用
toRef
和 toRefs
可以用来复制 reactive
里面的属性然后转成 ref
,而且它既保留了响应式,也保留了引用
,也就是你从 reactive
复制过来的属性进行修改后,除了视图会更新,原有 ractive
里面对应的值也会跟着更新,如果你知道 浅拷贝
的话那么这个引用
就很好理解了,它复制的其实就是引用 + 响应式 ref
不加 s 和 加 s 的区别就是这样:
- toRef: 复制 reactive 里的单个属性并转成 ref
- toRefs: 复制 reactive 里的所有属性并转成 ref
下面我会为这两个属性举一些使用案例
使用方式
toRef
<template>
<h2>
reactive-greet: {
{
info.greet }}
</h2>
<h2>
toRef-greet: {
{
rGreet }}
</h2>
<button @click="onChangeGreet">更换问候语</button>
</template>
<script>
import {
reactive, toRef } from 'vue'
export default {
setup() {
let info = reactive(<