VueUse 中文文档:Best Practice 最佳实践

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()

即便有些函数没有实现卸载,一个常规的办法是使用effectScopeAPI,比如:

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!')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值