VueUse - a Vue3 tool library that improves development efficiency, allowing you to get off work early

VueUse - a Vue3 tool library that greatly improves development efficiency, allowing you to get off work early

Follow the WeChat public account "Front-End Detective" for more exciting content!
insert image description here

foreword

VueUse is a collection of basic Vue composition utility functions implemented based on the Composition API.

VueUse may be inspired by react-use. It can be regarded as a vue version of hook. Vue Compostion API supports better logical separation, so that these commonly used tools can be reused, allowing you to quickly build rich applications , greatly improve your development efficiency, and avoid encapsulating some commonly used functions by yourself, such as: anti-shake, throttling, timer, etc.

A few days ago, by chance, I saw that VueUse has been widely used in the source code of the Element-plus component library, so I can boldly use it in the project.

Official website address: https://vueuse.org/

1. Features

Seamless Migration: Support both Vue2 and Vue3
Support On-demand Import: Only take what you want
Strong Type: Written in TypeScript, with TS Docs
Flexible: Configurable event filter
No need to package: Support CDN way to import
Rich features: Up to now, you can choose from 180+ functions.
Friendly SSR: It works perfectly with server-side rendering/generation.
Interactive demo: Function documentation also comes with interactive demo.
Additional plug-ins: Support Router, Firebase, RxJS and other plug-ins

2. Installation

command install

npm

npm i @vueuse/core

yarn

yarn add @vueuse/core

CDN introduction

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

Exposed globally as window.VueUse.

Three, use

The functions in VueUse are very rich, and we may not be able to use every function function, so which function function we use can be introduced in the component as needed. For example: Below we will introduce how to use several commonly used functions in combination with the code.

1, useMouse - get the mouse position

useMouse is a method to monitor the mouse position changes in real time and return the current mouse position coordinates x, y.

First look at the type declaration of useMouse:

export interface MouseOptions extends ConfigurableWindow {
    
    
  // 鼠标的位置是相对页面还是浏览器,默认是页面
  type?: "page" | "client"
 	// 监听 `touchmove` 事件,用于移动端,默认true
  touch?: boolean
 	// 触发`touchend`事件时重置为初始值,默认false
  resetOnTouchEnds?: boolean
  // 可以设置初始值
  initialValue?: Position
}
// 源类型是鼠标还触摸
export declare type MouseSourceType = "mouse" | "touch" | null

export declare function useMouse(options?: MouseOptions): {
    
    
  x: Ref<number>
  y: Ref<number>
  sourceType: Ref<MouseSourceType>
}
export declare type UseMouseReturn = ReturnType<typeof useMouse>

demo code:

<template>
    <div>
        <p>x的值:{
   
   { x }}</p>
        <p>y的值:{
   
   { y }}</p>
    </div>
</template>

<script lang="ts" setup>
    import {
      
       useMouse } from '@vueuse/core';

    const {
      
       x, y } = useMouse({
      
      
        type: 'page',
        touch: true,
        resetOnTouchEnds: false,
        initialValue: {
      
      
            x: 100,
            y: 200
        }
    })
</script>

Renderings:
insert image description here

2. useCounter - a basic counter with useful functions.

First look at the type declaration of useCounter:

// options配置类型
export interface UseCounterOptions {
    
    
  min?: number
  max?: number
}
export declare function useCounter(
	// 初始值
  initialValue?: number,
   // 设置最大值最小值
  options?: UseCounterOptions
): {
    
    
  // 计数器
  count: Ref<number>
  // 递增函数方法,方法里面可以传计数器步长,接受整数,小数,负数
  inc: (delta?: number) => number
  // 递减函数方法,方法里面可以传计数器步长,接受整数,小数,负数
  dec: (delta?: number) => number
  get: () => number
  // 设置计数器
  set: (val: number) => number
  // 重置计数器
  reset: (val?: number) => number
}

demo code:

<template>
    <div>
        <p>Count: {
   
   { count }}</p>
        <button @click="inc()">Increment</button>
        <button @click="dec()">Decrement</button>
        <button @click="inc(5.5)">Increment (+5.5)</button>
        <button @click="dec(5)">Decrement (-5)</button>
        <button @click="set(100)">Set (100)</button>
        <button @click="reset()">Reset</button>
    </div>
</template>

<script setup lang="ts">
    import {
      
       useCounter } from '@vueuse/core';

    const {
      
       count, inc, dec, set, reset } = useCounter(1)
</script>

Renderings:
insert image description here

3. useLocalStorage, useStorage - responsive localized storage, used for local data persistence.

By default, useStorage will intelligently use the appropriate serializer based on the data type of the default value provided. For example, JSON.stringify / JSON.parse will be used for objects, Number.toString / parseFloat for numbers, etc. That is to say, when we used
localStorage/sessionStorage to store an object before, we had to use JSON.stringify to serialize the object ourselves. Now using useLocalStorage will automatically serialize it for us according to the data type we pass in.

useLocalStorage, useSessionStorage, and useStorage have the same usage.

demo code:

<template>
    <div>
        <p>名称:{
   
   { state.name }}</p>
        <p>定位:{
   
   { state.type }}</p>
        <p>阵营:{
   
   { state.camp }}</p>

        <button @click="handleLocalStorage">UseLocalStorage</button>
        <button @click="handleReset">Reset</button>
    </div>
</template>

<script setup lang="ts">
import {
      
       useLocalStorage } from '@vueuse/core';

const state = useLocalStorage('my-lol', {
      
      
    name: '泰达米尔',
    type: '战士',
    camp: '弗雷尔卓德'
})

// 如果没有初始值时,可以设置null
// const state = useLocalStorage('my-lol', null)

const handleLocalStorage = () => {
      
      
    // 给LocalStorage my-lol重新赋值
    state.value = {
      
      
        name: '深渊巨口',
        type: '射手',
        camp: '虚空之地'
    }
}
// 删除LocalStorage my-lol的值
const handleReset = () => {
      
      
    state.value = null
}
</script>

useStorage defaults to localStorage.

import {
    
     useStorage } from '@vueuse/core'

// 对象类型
const state = useStorage('my-store', {
    
     hello: 'hi', greeting: 'Hello' })

// 布尔类型
const flag = useStorage('my-flag', true) 

// 数字类型
const count = useStorage('my-count', 0) 

// 使用sessionStorage
const id = useStorage('my-id', 'some-string-id', sessionStorage) 

// 删除某个key值
state.value = null

4, useDebounceFn - anti-shake

When the event is continuously triggered, the event processing function will only be executed once if no more events are triggered within a certain period of time. If the event is triggered again before the set time arrives, the delay will start again.

demo code:

<template>
    <p> {
   
   { counter }}</p>

    <button @click="clickedFn">UseDebounceFn</button>
</template>

<script setup lang="ts">
    import {
      
       ref } from 'vue'
    import {
      
       useDebounceFn } from '@vueuse/core'

    const counter = ref(0)
    // 第三个参数为最大等待时间,类似于 lodash debounce
    const debouncedFn = useDebounceFn(() => {
      
      
        counter.value += 1
    }, 1000, {
      
       maxWait: 5000 })

    const clickedFn = () => {
      
      
        debouncedFn()
    }
</script>

insert image description here

5、useTitle

Set the title of the webpage, which is the encapsulation of document.title.

demo code:

<template>
   <p>{
   
   { title }}</p>
</template>

<script setup lang="ts">
import {
      
       ref, computed } from 'vue';
import {
      
       useTitle } from '@vueuse/core';

const name = ref('Hello');
// 动态监听title的变化
const title = computed(() => {
      
      
    return `${ 
        name.value}--Hello`;
})

useTitle(title); // Hello--Hello
name.value = 'Hi'; // Hi--World
</script>

Source code analysis of useTitle:

MaybeRef is a type tool

type MaybeRef<T> = Ref<T> | T

MaybeRef is widely used in VueUse to support optional responsive parameters.

import {
    
     ref, watch } from 'vue';
import {
    
     MaybeRef } from '@vueuse/core';

export function useTitle(
	newTitle: MaybeRef<string | null | undefined> 
) {
    
    
  const title = ref(newTitle || document.title);

  watch(title, (t) => {
    
    
    if(t != null) {
    
    
      document.title = t
    }
  }, {
    
     immediate: true })

  return title
}

postscript

Because VueUse has many functions, here we briefly introduce a few commonly used functions. For more functions, you can go to the VueUse official website to learn and use them. In my study and use, I can point out the inappropriate places, and everyone can learn together. For more exciting content, you can scan the QR code below and follow my WeChat public account "Front Detective"!
insert image description here

Guess you like

Origin blog.csdn.net/qq_39327418/article/details/122527337