Vue 创建自定义 ref 函数 customRef
customRef 用于:创建一个自定义的 ref 函数,并对其依赖项跟踪和更新触发进行显式控制。
使用 customRef 创建自定义 ref 函数
// 创建自定义 ref 函数
function myRef(value) {
return customRef((track, trigger) => {
return {
get() {
track(); // 通知 Vue 追踪 value 的变化
return value; // 返回 value 值
},
set(newValue) {
value = newValue; // 修改 value 值
trigger(); // 通知 Vue 重新解析模板
}
}
})
}
// 使用自定义 ref 函数
let content = myRef('测试鸭');
自定义 ref 实现防抖效果:
<template>
<inp