解构
大多数vueuse中的函数都返回了一个对象,对象的属性值都是ref,所以可以通过es6的解构赋值直接获取某个属性,这个属性值是ref对象。例子如下:
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())
// "x" and "y" will be auto unwrapped, no `.value` needed
console.log(mouse.x)
区别:前者在获取的时候可以进行解构而不失去响应性,后者则不能解构。但是前者又需要加.value,后者则不需要。
清除副作用
就像Vue的watch跟computed对于组件被卸载之后的处理一样,当组件被卸载的时候,vueuse的函数会自动清除副作用。
比如,组件卸载(unmounted)的时候,useEventListener 将会自动调用 removeEventListener方法。
// will cleanup automatically
useEventListener('mousemove', () => {})
所有的vueuse函数都会遵循这个规范。一些函数会返回stop函数,用于手动清除副作用。就像watch函数一样。比如
const stop = useEventListener('mousemove', () => {})
// ...
// unregister the event listener manually
stop()
不是所有函数都会返回stop方法,所以更通用的做法是使用Vue中的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()
响应式参数
在vue中,我们通过setup方法来构建一个数据跟逻辑的连接(这句话的理解是,如果在没有setup的vue2中,逻辑都是放在方法中的,在vue3已经跟写脚本差不多了,所以现在能称为逻辑,而不是方法。),回到正文。为了拓展性,大多数vueuse提供的函数都接收ref,因为ref是具有响应性。
非响应式参数 useTitle组合式Api帮助你获取跟设置当前页面的文档titile属性。代码如下:
const isDark = useDark()
const title = useTitle('Hello')
console.log(document.title) // "Hello"
watch(isDark, () => {
title.value = isDark.value ? '🌙 Good evening!' : '☀️ Good morning!'
})
ref参数 你可以传递一个ref到useTitle取代之前通过修改useTitle返回的title的做法。如下:
const isDark = useDark()
const title = computed(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')
useTitle(title)
响应式getter参数 从9版本以上开始,我们推荐一个新的规范,通过传递响应式getter作为参数,这个特性跟响应式对象和响应式语法糖(废弃进程中)搭配使用的效果很好。
const isDark = useDark()
useTitle(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')