让开发事半功倍的VueUse

什么是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的值,

d

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值