toRef
- 如果原始对象是非响应式的就不会更新视图 数据是会变的
- 如果原始对象是响应式的是会更新视图并且改变数据的
<template>
<div>
<button @click="change">按钮</button>
{{state}}
</div>
</template>
<script setup lang="ts">
import { toRef } from 'vue'
const obj = {
zs: 1,
ls: 1
}
const state = toRef(obj, 'zs') //zs 转化为响应式对象
const change = () => {
state.value++
console.log(obj, state);
}
</script>
toRefs
- 可以批量创建ref对象主要是方便解构使用
<template>
<div>
<button @click="change">按钮</button>
{{state}}
</div>
</template>
<script setup lang="ts">
import { reactive, toRefs } from 'vue'
const obj = reactive({
zs: 1,
ls: 1
})
let { zs, ls } = toRefs(obj)
ls.value++
console.log(zs, ls);
</script>
toRaw
- 将响应式对象转化为普通对象
<template>
<div>
<button @click="change">按钮</button>
</div>
</template>
<script setup lang="ts">
import { reactive, toRaw } from 'vue'
const obj = reactive({
zs: 1,
ls: 1
})
const state = toRaw(obj)
// 响应式对象转化为普通对象
const change = () => {
console.log(obj, state);
}
</script>