unref、isRef、toRef、toRefs

unref() 如果参数是一个ref则返回它的value,否则返回参数本身
unref(val) 相当于val=isRef(val)?val.value:val

  function initialCount(value: number | Ref<number>) {
    // Make the output be true
    console.log(value === 10)
  }

  const initial = ref(10)

  initialCount(unref(initial))  // 必然输出true

isref() 检查一个值是否是一个ref对象
toRef、toRefs的本质是引用,修改响应式数据,会影响到原始数据,视图不会更新

toRef 一次仅能设置一个数据,接收两个参数,第一个参数是哪个对象,第二个参数是对象的哪个属性
toRefs 作用是将响应式对象中所有属性转换为单独的响应式数据,将对象中的每个属性都做一次ref操作,使每个属性都具有响应式。

const state = reactive({
  foo: 1,
  bar: 2,
})
// const fooRef = toRef(state,'foo')
const fooRef = toRefs(state).foo

 

fooRef.value++
console.log(state.foo === 2)


state.foo++
console.log(fooRef.value === 3)

 

<script setup lang="ts">
import { reactive,toRefs } from "vue"

function useCount() {
  const state = reactive({
    count: 0,
  })

  function update(value: number) {
    state.count = value
    console.log(state.count)
  }

  return {
    state:toRefs(state), // toRef使得state中每个属性都具有响应式
    update,
  }
}

const { state: { count }, update } = useCount()

</script>

<template>
  <div>
    <p>
      <span @click="update(count-1)">-</span>
      {{ count }}
      <span @click="update(count+1)">+</span>
    </p>
  </div>
</template>
展开运算符:
响应式对象的处理,是加给对象的,如果对对象做了展开操作,那么就会丢失响应式的效果。

<template>
  <button @click="name='张三'">修改名字</button>{{name}}
</template>

<script lang='ts'>

import { reactive, toRefs } from 'vue'
export default {
  setup() {
    const user = reactive<any>({
      name: '小明',
      age: 10,
      addr: {
        province: '山东',
        city: '青岛'
      }
    })
    return {
      ...toRefs(user)
    }
  }
}
</script>

 

posted on 2023-01-29 17:48  稳住别慌  阅读(8706)  评论(0编辑  收藏  举报