Vue 生态资源系列文章更新中,后续将陆续整理更新vue生态下优秀的资源,欢迎大家关注
是什么
VueUse 是基于 Vue组合式API 的工具函数库,支持Vue2/Vue3
特性一览
- 功能丰富,200+ 函数可用,文档 DEMO 齐全,复制即用
- 无缝迁移,兼容 vue2 vue3, 通用组合式API
- 全量支持 tree-shaking,随心引用
- 采用了TypeScript进行编写并且带有完整的TS文档,有良好的TS支持能力
- 灵活,将 ref 作为参数传递,支持可自定义、可配置的事件过滤器和目标
- 支持CDN,无需打包
- SSR友好,可用于服务端渲染场景
- 附加组件丰富
VueUse 是如何实现在 vue2/3 中通用 组合式API的?
Vue3引入了组合式API的概念。在vue2中,基于composition-api插件,也能在Vue2项目使用组合式API。
为了让更多的用户能够使用VueUse, VueUse实现了vue-demi , 它通过判断用户安装环境,Vue2项目 引用composition-api插件,Vue3项目引用官方包 ,这样Vue2用户也能用上VueUse了
如何使用
- 安装包
npm i @vueuse/core
- 使用CDN
<script src="https://unpkg.com/@vueuse/shared"></script>
<script src="https://unpkg.com/@vueuse/core"></script>
// 通过 window.VueUse 调用
-
vue2 Demo
最佳实践
解构取值
VueUse 中的大多数函数都返回一个 refs 对象,可以使用 ES6 的对象解构语法来获取所需的内容。例如:
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)
副作用清理
VueUse 的功能与Vue的watch、computed一样,也会在卸载组件时自动清除副作用。
例如,useEventListener 将在卸载组件时自动调用 removeEventListener
// will cleanup automatically
useEventListener('mousemove', () => {})
所有 VueUse 函数都会如此。
如果要手动清理副作用,某些函数会像watch一样返回副作用清理函数,直接调用即可完成清理。例如:
const stop = useEventListener('mousemove', () => {})
// ...
// unregister the event listener manually
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()
可以在此 RFC 中了解有关效果范围的更多信息.
将引用作为参数传递
在 Vue 中,我们使用 setup() 函数来构造数据和逻辑之间的“连接”。为了使它变得灵活,大多数 VueUse 函数也包含参数的 ref 版本。
以useTitle为例:
正常使用
通常 useTitle返回一个页面标题的引用。当为 ref 分配新值时,它会自动更新标题。
const isDark = useDark()
const title = useTitle('Set title')
watch(isDark, () => {
title.value = isDark.value ? '🌙 Good evening!' : '☀️ Good morning!'
})
关联使用
可以传递一个 ref 对象,使其绑定到页面标题(useTitle),形成关联。
const isDark = useDark()
const title = computed(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')
useTitle(title)
以响应式Getter作为参数
从 VueUse 9.0 开始,我们可以将 响应式函数 作为参数来传递。
const isDark = useDark()
useTitle(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')