让开发事半功倍的VueUse

VueUse是一个提供Composition API实用函数的库,适用于Vue 2和3,拥有丰富的功能,如防抖节流、监听外部点击、创建全局状态等。它支持SSR/SSG,并可通过npm或CDN安装。示例中展示了如何使用throttleFilter、debounceFilter、onClickOutside、createGlobalState等工具函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是VueUse

VueUse不是Vue.use,它是为Vue 2和3服务的是一组基于Composition API的实用函数。是目前世界上Star最高的同类型库之一。他功能丰富,与服务器端渲染/生成完美配合,无需任何捆绑程序可通过CDN直接使用

官网:

https://vueuse.org/

安装

npm
npm i @vueuse/core
cdn
<script src="https://unpkg.com/@vueuse/shared"></script> 
<script src="https://unpkg.com/@vueuse/core"></script>

使用导入

从@vueuse/core中导入所需要的使用的功能

import { useLocalStorage, useMouse, usePreferredDark } from '@vueuse/core'

export default {
  setup() {
    // tracks mouse position
    const { x, y } = useMouse()

    // is user prefers dark theme
    const isDark = usePreferredDark()

    // persist state in localStorage
    const store = useLocalStorage(
      'my-storage',
      {
        name: 'Apple',
        color: 'red',
      },
    )

    return { x, y, isDark, store }
  },
}

上面从 VueUse 当中导入了三个函数,useLocalStorage, useMouse, usePreferredDark 。

useLocalStorage 是一个用来持久化数据的方法,他会把数据持久化到本地存储中。

useMouse 是一个监听当前鼠标坐标的一个方法,他会实时的获取鼠标的当前的位置。

usePreferredDark 是一个判断用户是否喜欢深色的方法,他会实时的判断用户是否喜欢深色的主题。

VueUse提供了大多数的工具函数

防抖节流: throttleFilter and debounceFilter

import { debounceFilter, throttleFilter, useLocalStorage, useMouse } from '@vueuse/core'

// changes will write to localStorage with a throttled 1s
const storage = useLocalStorage('my-key', { foo: 'bar' }, { eventFilter: throttleFilter(1000) })

// mouse position will be updated after mouse idle for 100ms
const { x, y } = useMouse({ eventFilter: debounceFilter(100) })

上述代码是throttleFilter and debounceFilter

throttleFilter:通过节流的方式去改变localStore的值,

debounceFilter:对于鼠标的位置更新使用防抖的方法,一百毫秒后进行更新

监听元素外部的点击: onClickOutside

基础用法
<template>
  <div ref="target">
    Hello world
  </div>
  <div>
    Outside element
  </div>
</template>

<script>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'

export default {
  setup() {
    const target = ref(null)

    onClickOutside(target, (event) => console.log(event))

    return { target }
  }
}
</script>

在当前页面的使用:

target:当前的组件实例,

onClickOutside:监听元素外部的点击

组件使用
<script setup>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'

const el = ref()

function close () {
  /* ... */
}

onClickOutside(el, close)
</script>

<template>
  <div ref="el">
    Click Outside of Me
  </div>
</template>

component组件:

<script setup>
import { OnClickOutside } from '@vueuse/components'

function close () {
  /* ... */
}
</script>

<template>
  <OnClickOutside @trigger="close">
    <div>
      Click Outside of Me
    </div>
  </OnClickOutside>
</template>


这里的 OnClickOutside 函数是一个组件,不是一个函数。需要package.json 中安装了 @vueuse/components。这个是绑定的无渲染组件

使用了 onClickOutside 函数,这个函数会在点击元素外部时触发一个回调函数。也就是这里的 close 函数。

创建全局状态:createGlobalState

// store.js
import { createGlobalState, useStorage } from '@vueuse/core'

export const useGlobalState = createGlobalState(
  () => useStorage('vueuse-local-storage', {
      name:"kepler",
      sex:'男'
     }
  ),
)
import { useGlobalState } from './store'

export default defineComponent({
  setup() {
    const state = useGlobalState()
    console.log(state.name) // kepler
    state.name = 'kepler_明'
    console.log(state.name) // kepler_明
    return { state }
  },
})

这就是一个简单的状态共享,而需要修改的时候传一个参数就可以进行修改

多久时间前: useTimeAgo

import { useTimeAgo } from '@vueuse/core' 
const timeAgo = useTimeAgo(new Date(2022, 8, 16))

获取当前的实时时间戳:timestamp

import { useTimestamp } from '@vueuse/core' 
const timestamp = useTimestamp()

记录上次更改的时间戳:useLastChanged

使用:
import { timestamp, useLastChanged, useTimeAgo } from '@vueuse/core'

const a = ref(0)

const lastChanged = useLastChanged(a)
const ms = useLastChanged(a, { initialValue: timestamp() - 1000 * 60 * 5 }) 

a.value = 1

const timeago = useTimeAgo(ms) 

console.log(timeago.value) // 打印更新周期比如:2 分钟前
console.log(lastChanged.value)  // 打印更新的毫秒数

拖动 useDraggable

<script setup>
import { ref } from 'vue'
import { useDraggable } from '@vueuse/core'

const el = ref(null)

const { x, y, style } = useDraggable(el, {
  initialValue: { x: 40, y: 40 },
})
</script>

<template>
  <div ref="el" :style="style" style="position: fixed">
    Drag me! I am at {{x}}, {{y}}
  </div>
</template>

el 拖动的元素,

initialValue:设置初始的位置

调整边框获取边框的信息 useElementBounding

<template>
  <div ref="el" />
</template>

<script>
import { ref } from 'vue'
import { useElementBounding } from '@vueuse/core'

export default {
  setup() {
    const el = ref(null)
    const { x, y, top, right, bottom, left, width, height } = useElementBounding(el)
    /*
    height: 249
    bottom: 397
    left: 455.6000061035156
    right: 809.6000061035156
    top: 148
    width: 354
    x: 455.6000061035156
    y: 148
    */
    return {
      el,
      /* ... */
    }
  }
}
</script>

获取鼠标的位置 useMouseInElement

<template>
  <div ref="target">
    <h1>Hello world</h1>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useMouseInElement } from '@vueuse/core'

export default {
  setup() {
    const target = ref(null)

    const { x, y, isOutside } = useMouseInElement(target)

    return { x, y, isOutside }
  }
}
</script>

使用蓝牙:useBluetooth

import { useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
})

<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

使用日期格式: useDateFormat

<script setup>
import {useDateFormat } from '@vueuse/core'

const formatted = useDateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
// 2022-08-18 16:00:00
</script>

<template>
  <div>{{ formatted }}</div>
</template>

哈哈哈,还有很多很多的工具函数点击这里来看,自己慢慢琢磨吧

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值