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>

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/128622108