反转基因福娃 发表于 2025-4-19 13:24:32

Vue —— 实用的工具函数

相应式数据管理

1. toRef 和 torefs

作用: 将相应式对象的属性转换为 ref,保持解构后的相应性
场景: 解构 reactive 对象时避免丢失相应性
示例:
import { reactive, toRef, toRefs } from 'vue';

const state = reactive({ x: 1, y: 2 });

// 解构单个属性
const xRef = toRef(state, 'x');// xRef.value 始终同步 state.x

// 解构所有属性
const { y } = toRefs(state); // y.value 同步 state.y
2. shallowRef 和 shallowReactive

作用: 创建浅层相应式数据(只跟踪顶层的属性变革)。
场景: 优化性能,避免深度监听大对象
示例:
const shallowState = shallowReactive({
        nested: { data : 'value' }// 修改 nested.data 不会触发响应式更新
})

const shallowCount = shallowRef({ value : 0 });
shallowCount.value.value = 1; // 不会触发响应式更新
3. markRaw

作用: 标记对象为 “ 非相应式 ”,避免被 Vue 转换为署理。
场景: 处置惩罚第三方库对象或性能敏感数据。
示例:
const rawObject = markRaw({ data : 'static' });
const state = reactive({ rawObject }); // rawObject 不会被代理
依赖追踪与副作用

1. computed

作用: 创建依赖其他相应式数据的盘算属性。
场景: 缓存复杂盘算结果,避免重复盘算
示例:
const count = ref(0);
const doubled = computed(()=> count.value * 2);

console.log(doubled.value);// count 变化后自动更新
2. watch 和 watchEffect

作用: 监听数据变革并实行副作用


[*]watch: 显式指定监听目标
[*]watchEffect: 主动追踪依赖
示例:
const count = ref(0);

// 监听 count 变化
watch(count, (newVal, oldVal)=>{
        console.log(`Count changed from ${oldVal} to ${newVal}`)
});

// 自动追踪依赖
watchEffect(() => {
        console.log(`Count is ${count.value}`);
})
类型判断与优化

1. unref

作用: 快速获取 ref 的值(如果是 ref 返回 .value,否则返回原值)。
场景: 简化 ref 宁静常值的混合处置惩罚
示例:
const x = ref(10);
const rawValue = 20;

console.log(unref(x));    // 10 不用x.value
console.log(unref(rawValue)); // 20
2. isRef 、isReactive 和 isProxy

作用: 判断变量类型


[*]isRef(value): 是否为 ref 对象
[*]isReactive(value): 是否为 reactive 创建的相应式对象
[*]isProxy(value): 是否为 reactive 或 readonly 署理
示例:
const count = ref(0);
const state = reactive({ x: 1 });

console.log(isRef(count));      // true
console.log(isReactive(state)); // true
console.log(isProxy(state));    // true
组件通信与生命周期

1. provide 和 inject

作用: 跨层级组件通报数据
场景: 避免逐层通报 props
示例:
// 父组件
import { provide } from 'vue';
provide('theme', 'dark');

// 子组件
import { inject } from 'vue';
const theme = inject('theme', 'light'); // 默认值 'light'
2. nextTick

作用: 在 DOM 更新后实行回调
场景: 操作更新后的 DOM 元素
示例:
import { nextTick } from 'vue';

const updateData = async () => {
        data.value = 'new value';
        await nextTick();
        console.log('DOM 已更新');
}
高级工具

1. useAttrs 和 useSlots

作用: 在 script setup 中访问组件的 attrs 和 slots
场景: 处置惩罚未声明为 props 的属性或动态插槽
示例:
<script setup>
import { useAttrs, useSlots } from 'vue';

const arrts = useAttrs();// 获取所有非 props 属性
const slots = useSlots();// 获取插槽内容
<script>
总结:合理利用这些工具,可以大幅度提拔代码的简洁性和可维护性,同时避免常见的相应式陷阱

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Vue —— 实用的工具函数