Destructuring
大部分VueUse
的函数返回都是响应式对象,使用 xxx.value
获取值
import { useMouse } from '@vueuse/core'
// "x" and "y" are refs
const { x, y } = useMouse()
console.log(x.value)
const mouse = useMouse()
console.log(mouse.x.value)
如果想使用对象属性的方式来访问,使用reactive()
import { reactive } from 'vue'
import { useMouse } from '@vueuse/core'
const mouse = reactive(useMouse())
console.log(mouse.x)
Side-effect Clean Up
VueUse
在组件被卸载时会自动卸载,不会带来副作用。
部分VueUse
函数也可以手动卸载,如果有被实现的话,比如:
const stop = useEventListener('mousemove', () => {})
// unregister the event listener manually
stop()
即便有些函数没有实现卸载,一个常规的办法是使用effectScope
API,比如:
import { effectScope } from 'vue'
const scope = effectScope()
scope.run(() => {
// ...
useEventListener('mousemove', () => {})
onClickOutside(el, () => {})
watch(source, () => {})
})
// all composables called inside `scope.run` will be disposed
scope.stop()
关于effect scope
参考资料。
Passing Ref as Argument
在Vue
应用中,我们使用setup()
函数来创建数据和逻辑的“连接”。为了更好的灵活性,很多VueUse
函数同样支持接收响应式的参数。
Normal usage
通常useTitle
返回一个响应式页面标题变量,当你为该变量赋新值时,它将自动更新页面的标题。
const isDark = useDark()
const title = useTitle('Set title')
watch(isDark, () => {
title.value = isDark.value ? '🌙 Good evening!' : '☀️ Good morning!'
})
Connection usage
如果你想创建标题与暗色模式的“连接”,你可以传递一个响应式引用,使其绑定到页面的标题。
const isDark = useDark()
const title = computed(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')
useTitle(title)
Reactive Getter
自VueUse 9.0以来,我们引入了一种新的惯例,将“Reactive Getter”作为参数传递。同样能实现相应的效果。
const isDark = useDark()
useTitle(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')