Vue toRef抽取出来单个的ref, toRefs 解构,toRaw

Posted 安果移不动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue toRef抽取出来单个的ref, toRefs 解构,toRaw相关的知识,希望对你有一定的参考价值。

toRef

单独抽出某个遍历为Ref

 这样是不行的 必须为相应对象才行

<template>
  <div>
     man 
     like 
  </div>
  <hr>
  <div>
    <button @click="change">修改</button>
  </div>
</template>
<script setup lang="ts">
import toRef, reactive, toRefs, toRaw from 'vue'



const man = reactive(name: "zhangsan", age: 18, like: "Jk")
const like=toRef(man,'like')

const change = () => 
  like.value = "洛丽塔"


</script>

toRefs

可以通过toref演变出来toRefs

const toRefs = <T extends object>(object: T) => 
  const map: any = 
  for (const key in object) 
    map[key] = toRef(object, key)
  
  return map

修改全部代码

<template>
  <div>
     man 
     like --name-- age
  </div>
  <hr>
  <div>
    <button @click="change">修改</button>
  </div>
</template>
<script setup lang="ts">
import toRef, reactive, toRaw from 'vue'


const man = reactive(name: "zhangsan", age: 18, like: "Jk")

const toRefs = <T extends object>(object: T) => 
  const map: any = 
  for (const key in object) 
    map[key] = toRef(object, key)
  
  return map


const name, age, like = toRefs(man)

const change = () => 
  like.value = "洛丽塔"


</script>

 用到vue的toRefs 就行了

<template>
  <div>
     man 
     like --name-- age
  </div>
  <hr>
  <div>
    <button @click="change">修改</button>
  </div>
</template>
<script setup lang="ts">
import toRef, reactive, toRaw,toRefs from 'vue'


const man = reactive(name: "zhangsan", age: 18, like: "Jk")



const name, age, like = toRefs(man)

const change = () => 
  like.value = "洛丽塔"


</script>

toRaw 也很好理解 是将ref对象转换为普通对象

 

<template>
  <div>
     man 
  </div>
  <hr>
  <div>
    <button @click="change">修改</button>
  </div>
</template>
<script setup lang="ts">
import toRef, reactive, toRaw, toRefs from 'vue'


const man = reactive(name: "zhangsan", age: 18, like: "Jk")


const change = () => 
  console.log(man, toRaw(man))


</script>

这个其实是取出来的__v_raw

<template>
  <div>
     man 
  </div>
  <hr>
  <div>
    <button @click="change">修改</button>
  </div>
</template>
<script setup lang="ts">
import toRef, reactive, toRaw, toRefs from 'vue'


const man = reactive(name: "zhangsan", age: 18, like: "Jk")


const change = () => 
  console.log(man, toRaw(man), man['__v_raw'])


</script>

 

以上是关于Vue toRef抽取出来单个的ref, toRefs 解构,toRaw的主要内容,如果未能解决你的问题,请参考以下文章

vue3的ref和reactive以及toRef和toRefs的区别。

vue3.2 响应式之 ref reactive toRef toRefs

vue3.2 响应式之 ref reactive toRef toRefs

Vue 3 之:弄清 ref reactive toRef toRefs

[vue3新特性] 12.组合api——13.toRef和toRefs

敲黑板!vue3重点!一文了解Composition API新特性:reftoReftoRefs