记录
customRef
- Debounced | example
ts
import { Ref, customRef } from 'vue'
function useDebouncedRef<T>(value: T, delay = 200): Ref<T> {
let timeout: ReturnType<typeof setTimeout>
return customRef((track, trigger) => {
return {
get() {
track()
return value
},
set(newValue: T) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger()
}, delay)
},
}
})
}
vue
<script setup lang="ts">
import { useDebouncedRef } from './debouncedRef'
const text = useDebouncedRef('hello')
</script>
<template>
<p>{{ text }}</p>
<input v-model="text" />
</template>
tsx
import { defineComponent } from 'vue'
import { useDebouncedRef } from './debouncedRef'
export default defineComponent({
setup() {
const text = useDebouncedRef('hello', 1000)
return () => (
<>
<p>{text.value}</p>
<input v-model={text.value} />
</>
)
},
})
在不失去反应性的情况下解构属性
vue
<script setup lang="ts">
import { toRefs } from 'vue'
const props = withDefaults(
defineProps<{
event: object
address: string
}>(),
{}
)
const { address } = toRefs(props)
</script>
<template>
<div class="font-medium bg-gray-100 text-gray-700 py-3 px-3 rounded">
{{ address }}
</div>
</template>
自定义指令
vue
<script setup lang="ts">
import { ref, vModelText } from 'vue'
const value = ref('')
// 为' v-model '指令定义一个名为'capitalize '的自定义修饰符
vModelText.beforeUpdate = function (el, { value, modifiers }) {
// 检查' v-model '指令中是否存在' capitalize '修饰符
if (value && modifiers.capitalize) {
el.value = el.value.toUpperCase()
}
}
</script>
<template>
<input type="text" v-model.capitalize="value" />
</template>
性能标记
ts
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
if (process.env.NODE_ENV === 'development') {
app.config.performance = true
}
app.mount('#app')
组件外部调用方法
vue
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import ChildComponent from './B.vue'
const childComponent = ref()
onMounted(() => {
childComponent.value.doSomething()
})
</script>
<template>
<ChildComponent ref="childComponent" />
</template>
vue
<script setup lang="ts">
function doSomething() {
// do smething
console.log(123)
}
defineExpose({ doSomething })
</script>
<template>
<h1>Child component</h1>
</template>
pinia 持久化
pinia-plugin-persistedstate