欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > toRef,toRefs,toRaw

toRef,toRefs,toRaw

2025/3/13 13:09:33 来源:https://blog.csdn.net/anxin_wang/article/details/143696020  浏览:    关键词:toRef,toRefs,toRaw

假设有一个响应式对象 state,我们只想独立地访问和修改其中的某个属性,比如 count:

toRef

import { reactive, toRef } from 'vue';// 创建一个响应式对象
const state = reactive({count: 0,message: "Hello Vue 3"
});// 使用 toRef 创建 count 的引用
const countRef = toRef(state, 'count');// 现在 countRef 是一个响应式的引用,修改它会更新 state.count
countRef.value++; // state.count 将变成 1console.log(state.count); // 输出:1

toRefs

import { reactive, toRefs } from 'vue';const state = reactive({count: 0,message: "Hello Vue 3"
});// 使用 toRefs 将对象的属性全部转换为 ref
const { count, message } = toRefs(state);count.value++; // state.count 也将更新

toRaw

import { reactive, toRaw } from 'vue';// 创建一个响应式对象
const state = reactive({count: 0,message: "Hello Vue 3"
});// 获取响应式对象的原始版本
const rawState = toRaw(state);console.log(rawState); // 输出非响应式对象:{ count: 0, message: "Hello Vue 3" }// 修改 rawState 的属性,不会触发响应性更新
rawState.count++;
console.log(state.count); // 输出 0,因为修改了非响应式对象,不会影响响应式状态

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词