Specific usage of Vue's new toy VueUse

Specific usage of Vue's new toy VueUse

Preface

Last time, when I was watching the front-end early chat conference, Mr. You once again mentioned a library called VueUse. Out of curiosity, I clicked to take a look. Wow, I'm just like that. Isn't this what I once wanted to write a Vue version of the hooks library myself? (Because I think vue3 and hooks are too similar) But I'm not very good at it yet, and now you have shattered my dream. Let's take a look at it together! VueUse author Anthony Fu shares composable Vue

What is VueUse

VueUse is not Vue.use. It is a set of common tools for Vue Composition API serving Vue 2 and 3. It is one of the highest-rated libraries of its kind in the world. Its original intention was to make all JS APIs that did not originally support responsiveness responsive, saving programmers the trouble of writing related code themselves.

VueUse is a collection of utility functions based on the Composition API. In layman's terms, this is a tool function package that can help you quickly implement some common functions so that you don't have to write them yourself and solve repetitive work content. And the opportunity Composition API is encapsulated. Let you be more comfortable with vue3.

Easy to use

Install VueUse

npm i @vueuse/core

Use Vue

// Import import { useMouse, usePreferredDark, useLocalStorage } 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 }
  }
}

Three functions are imported from VueUse above: useMouse, usePreferredDark, and useLocalStorage. useMouse is a method that monitors the current mouse coordinates. It will get the current position of the mouse in real time. usePreferredDark is a method to determine whether the user prefers dark colors. It will determine in real time whether the user likes dark themes. useLocalStorage is a method used to persist data, which will persist the data to local storage.

There are also the familiar anti-shake and throttling

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

// Change the value of localStorage in a throttled manner const storage = useLocalStorage('my-key', { foo: 'bar' }, { eventFilter: throttleFilter(1000) })

// Update the mouse position after 100ms const { x, y } = useMouse({ eventFilter: debounceFilter(100) })

There are also functions used in components

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

In the above example, the onClickOutside function is used, which triggers a callback function when clicking outside the element. That is the close function here. This is how it is used in component

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

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

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

Note⚠️ The OnClickOutside function here is a component, not a function. Requires @vueuse/components to be installed in package.json.

There are also functions for sharing global state

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

export const useGlobalState = createGlobalState(
  () => useStorage('vue-use-local-storage'),
)

//component.js
import { useGlobalState } from './store'

export default defineComponent({
  setup() {
    const state = useGlobalState()
    return { state }
  },
})

This is a simple state sharing. Expand a bit. By passing a parameter, you can change the value of the store.

Regarding fetch, the following is a simple request.

import { useFetch } from '@vueuse/core'

const { isFetching, error, data } = useFetch(url)

It also has many option parameters that can be customized.

// 100ms timeout const { data } = useFetch(url, { timeout: 100 })
// Request interception const { data } = useFetch(url, {
  async beforeFetch({ url, options, cancel }) {
    const myToken = await getMyToken()

    if (!myToken)
      cancel()

    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${myToken}`,
    }

    return {
      options
    }
  }
})

// Response interception const { data } = useFetch(url, {
  afterFetch(ctx) {
    if (ctx.data.title === 'HxH')
      ctx.data.title = 'Hunter x Hunter' // Modifies the resposne data

    return ctx
  },
})

More

For more information, see the VueUse documentation. There is also another vue-demi

This is the end of this article about the specific usage of Vue's new toy VueUse. For more relevant Vue VueUse content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue custom component (used by Vue.use()) is the usage of install
  • The principle and basic use of Vue.use() in Vue
  • A brief discussion on the vue.use() method from source code to usage
  • Usage of Vue.use() and installation

<<:  Analysis of the difference between bold <b> and <strong>

>>:  Understand the basics of Navicat for MySQL in one article

Recommend

MySQL explain obtains query instruction information principle and example

explain is used to obtain query execution plan in...

Zabbix monitors Linux hosts based on snmp

Preface: The Linux host is relatively easy to han...

JS implements multiple tab switching carousel

Carousel animation can improve the appearance and...

How to use default values ​​for variables in SASS

Variables defined in SASS, the value set later wi...

The meaning and calculation method of QPS and TPS of MySQL database

When doing DB benchmark testing, qps and tps are ...

Several commonly used single-page application website sharing

CSS3Please Take a look at this website yourself, ...

How to use HTML+CSS to create TG-vision homepage

This time we use HTML+CSS layout to make a prelim...

How to modify the location of data files in CentOS6.7 mysql5.6.33

Problem: The partition where MySQL stores data fi...

How to configure Java environment variables in Linux system

Configure Java environment variables Here, the en...

Detailed explanation of how Vue components transfer values ​​to each other

Table of contents Overview 1. Parent component pa...

MySql 5.6.36 64-bit green version installation graphic tutorial

There are many articles about MySQL installation ...

CSS3 countdown effect

Achieve results Implementation Code html <div ...

Talking about the practical application of html mailto (email)

As we all know, mailto is a very practical HTML ta...