preface

During the last Look at the Front End early chat, Ujada once again mentioned one of VueUse’s libraries. I was curious and clicked. Dude, I’m just gonna be dude. Isn’t there a time when I wanted to write a vue version of the hooks library myself? Because I think vue3 is like hooks. But I’m not so good at it. Now you’re blowing my dreams away. VueUse author Anthony Fu shares the combinable Vue_ bilibili

What is theVueUse

VueUse is a collection of utility functions based on the Composition API. In plain English, this is a package of utility functions that can help you quickly implement common functions without having to write them yourself. And encapsulation based on Composition API. Make you more comfortable in vue3.

Simple to fit

Install VueUse

npm i @vueuse/core
Copy the code

Using VueUse

/ / 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 }
  }
}
Copy the code

We import three functions from VueUse: useMouse, usePreferredDark, useLocalStorage. UseMouse is a method that listens to the current mouse coordinates. It will get the current mouse position in real time. UsePreferredDark is a method to determine whether a user likes a dark theme in real time. UseLocalStorage is a method for persisting data to local storage.

And the ones we’re familiar withImage stabilizationThe throttle

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

// Change localStorage by throttling
const storage = useLocalStorage('my-key', { foo: 'bar' }, { eventFilter: throttleFilter(1000)})// Update mouse position after 100ms
const { x, y } = useMouse({ eventFilter: debounceFilter(100)})Copy the code

There are also functions used in Component

<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>
Copy the code

In the example above, the onClickOutside function is used, which triggers a callback function when clicking outside the element. That’s the close function right there. This 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>
Copy the code

Note that the OnClickOutside function here at ⚠️ is a component, not a function. Need @vueuse/ Components installed in package.json.

There are also functions for global state sharing

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

export const useGlobalState = createGlobalState(
  () = > useStorage('vue-use-local-storage'),Copy the code
// component.js
import { useGlobalState } from './store'

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

This is a simple state sharing. Let me expand on that. You can change the value of store by passing a parameter.

There are aboutfetchBelow 👇 is a simple request.

import { useFetch } from '@vueuse/core'

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

It also has a number of options that you can customize.

/ / 100 ms timeout
const { data } = useFetch(url, { timeout: 100 })
Copy the code
// 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
    }
  }
})
Copy the code
// 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
  },
})
Copy the code

More and more

Read more about VueUse documentation, and there’s another project that you might need vue-Demi for