toRef
如果原始对象是非响应式的,就不会更新视图, 数据是会变的
<template>
<div>{{ person }}</div>
<div>{{ name }}</div>
<button @click="change">修改</button>
</template>
<script setup lang="ts">
import { toRef } from 'vue'
let person = { name: 'zs', age: 18 }
let name = toRef(person, 'name')
let change = () => {
name.value = '我改变了'
console.log(person, name)
}
</script>
但源数据是响应式对象时,可以更新,源数据也会被修改
<script setup lang="ts">
import { toRef, reactive } from 'vue'
let person = reactive({ name: 'zs', age: 18 })
let name = toRef(person, 'name')
let change = () => {
name.value = '我改变了'
console.log(person, name)
}
</script>
应用场景:主要是用在把对象中的某个属性单独拿出来,同时还能保证拿出来后与源数据仍然保存联动,依然还是一个响应式数据
toRefs
toRefs
就是一次可以解构出多个响应式数据
<template>
<div>{{ person }}</div>
<div>{{ name }}</div>
<div>{{ age }}</div>
<button @click="change">修改</button>
</template>
<script setup lang="ts">
import { toRef, reactive, toRefs } from 'vue'
let person = reactive({ name: 'zs', age: 18 })
let { name, age } = toRefs(person)
let change = () => {
name.value = '我改变了'
age.value = 20
console.log(person, name, age)
}
</script>
toRaw
把响应式对象变成普通对象
<template>
<div>{{ person }}</div>
<div>{{ obj }}</div>
<button @click="change">修改</button>
</template>
<script setup lang="ts">
import { toRaw, reactive } from 'vue'
let person = reactive({ name: 'zs', age: 18 })
let obj = toRaw(person)
let change = () => {
obj.age = 20
// 数据会改变,但是视图不会更新了
console.log(person, obj)
}
</script>