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