<template>
<!-- customRef、公共方法提取 -->
<div>
<input v-model="text" />
{{ text2[0].a }}
<button @click="myFun">按钮</button>
<dd @click="testFun('我的')">点击</dd>
</div>
</template>
<script>
import { useDebouncedRef, testFun } from './pub.js'
export default {
setup() {
let text = useDebouncedRef('hello')
let text2 = useDebouncedRef([{ a: 1 }])
function myFun() {
text.value = '中文提示'
text2.value = [{ a: 6666 }]
// text2.value.a = 555555555 //不会更新ui视图
}
return {
text,
text2,
myFun,
testFun
}
}
}
</script>
<style lang="scss" scoped></style>
import { customRef } from 'vue'
export function useDebouncedRef(value, delay = 200) {
// 请求异步数据
/*
requestData().then((res) => {
if (res) {
value = res.data
trigger()
}
})
*/
let timeout
return customRef((track, trigger) => {
return {
get() {
//这里不能发送网络请求,不然会死循环
track()
return value
},
set(newValue) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger()
}, delay)
}
}
})
}
export function testFun(a = 2) {
console.log(a, '222222222')
return a
}