编程知识 cdmana.com

5 vueuse library functions that can accelerate development

 picture

VueUse yes Anthony Fu An open source project of , It's for Vue Developers offer a lot of tools for Vue 2 and Vue 3 Basic Composition API Utility functions .

It has dozens of solutions , For common developer use cases , Such as tracking Ref change 、 Check element visibility 、 Simplify common Vue Pattern 、 keyboard / Mouse input, etc . It's a really good way to save development time , Because you don't have to add all these standard features yourself .

I like VueUse library , Because it really puts developers first in deciding which utilities to offer , And it's a well maintained Library , Because it is related to Vue Keep in sync with the current version of .

VueUse What utilities are there ?

If you want to see a complete list of each utility , I absolutely recommend that you go and see Official documents [1]. But to summarize ,VueUse There is 9 Two types of functions .

  1. Animation—— Contains easy to use transitions 、 Timeout and timing functions .
  2. Browser—— Can be used for different screen control 、 clipboard 、 Preference, etc .
  3. Component—— Provides shorthand for different component methods .
  4. Formatters—— Provide response time format function .
  5. Sensors—— To monitor different DOM event 、 Input events and network events .
  6. State—— Manage user status ( overall situation 、 The local store 、 Session storage ).
  7. Utility—— Different utility functions , Such as getter、 Conditions 、 Reference synchronization, etc .
  8. Watch—— More advanced types of observers , Such as a pausable observer 、 Retreat observer and condition observer .
  9. Misc—— Different types of events 、WebSockets and web workers The function of

Most of these categories contain several different functions , therefore VueUse It's very flexible for your usage , It's a great place to start building quickly Vue Applications .

In this tutorial , We'll take a look 5 Different VueUse function , So you can see how easy it is to work in this library .

But first of all , Let's add it to Vue In the project !

take VueUse Install to your Vue In the project

VueUse One of the most important characteristics of English is , It's compatible with just one package Vue 2 and Vue 3!

install VueUse There are two options npm or CDN

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

I suggest using NPM, Because its usage is easier to understand , But if we use CDN,VueUse Will be in the application through window.VueUse visit .

about NPM Installation , All functions can be refactored from using standard objects @vueuse/core Import , Visit like this .

import { useRefHistory } from '@vueuse/core'

Okay , Now we have installed VueUse, Let's use it in an application !

useRefHistory Tracking changes to responsive data

useRefHistory Tracking right Ref Every change you make , And store it in an array . This allows us to easily provide undo and redo capabilities for our applications .

Let's look at an example , We're building a text area that we want to be able to undo .

The first step is not to use VueUse Create our basic components in the case of —— Use ref、textarea And buttons for undo and redo .

<template>
<p>
<button> Undo </button>
<button> Redo </button>
</p>
<textarea v-model="text"/>
</template>

<script setup>
import { ref } from 'vue'
const text = ref('')
</script>

<style scoped>
button {
border: none;
outline: none;
margin-right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;;
}
</style>

then , Let's import useRefHistory function , And then from our text ref Extract from history、undo and redo Property to add VueUse. It's like calling useRefHistory And pass on our ref It's as simple as .

import { ref } from 'vue'
import { useRefHistory } from '@vueuse/core'

const text = ref('')
const { history, undo, redo } = useRefHistory(text)

Every time we ref When changes , This triggers an observer —— Update the history attribute .

then , So that we can really see what's going on , Let's print out the history in the template , At the same time, call our undo and redo function .

<template>
<p>
<button @click="undo"> Undo </button>
<button @click="redo"> Redo </button>
</p>
<textarea v-model="text"/>
<ul>
<li v-for="entry in history" :key="entry.timestamp">
{{ entry }}
</li>
</ul>
</template>

<script setup>
import { ref } from 'vue'
import { useRefHistory } from '@vueuse/core'
const text = ref('')
const { history, undo, redo } = useRefHistory(text)
</script>

<style scoped>
button {
border: none;
outline: none;
margin-right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;;
}
</style>

well , Let's run it . When we type in , Each character triggers a new entry in the history array , If we click undo/redo, We will go to the corresponding entry .

 picture

There are different options to add more to this feature . for example , We can go deep into the reaction object and limit the number of such historical entries .

const { history, undo, redo } = useRefHistory(text, {
deep: true,
capacity: 10,
})

For a complete list of options , Be sure to check the documentation .

onClickOutside Turn off mode

onClickOutside Detect any clicks outside of an element . According to my experience , The most common use of this feature is to turn off any mode or pop-up window .

Usually , We want our mode to block the rest of the page , To attract users' attention and limit errors . However , If they actually click on something outside of mode , We want it to shut down .

It takes only two steps to do this :

  1. Create a template reference for the element we want to detect
  2. Use this template reference to run onClickOutside

This is a use of onClickOutside A simple component with a pop-up window for .

<template>
<button @click="open = true"> Open Popup </button>
<div class="popup" v-if='open'>
<div class="popup-content" ref="popup">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis aliquid autem reiciendis eius accusamus sequi, ipsam corrupti vel laboriosam necessitatibus sit natus vero sint ullam! Omnis commodi eos accusantium illum?
</div>
</div>
</template>

<script setup>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
const open = ref(false) // state of our popup
const popup = ref() // template ref
// whenever our popup exists, and we click anything BUT it
onClickOutside(popup, () => {
open.value = false
})
</script>

<style scoped>
button {
border: none;
outline: none;
margin-right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;;
}
.popup {
position: fixed;
top: ;
left: ;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: rgba(, , , 0.1);
}
.popup-content {
min-width: 300px;
padding: 20px;
width: 30%;
background: #fff;
}
</style>

It turns out like this , We can use our buttons to open pop ups , Then click outside the pop-up content window to close it .

 picture

useVModel To simplify the v-model binding

Vue A common use case for developers is to create custom v-model binding . This means that our component accepts a value as prop, And whenever the value is modified , Our components send update events to the parent .

 picture

useVModel Function reduces it to just using the standard ref grammar . Suppose we have a custom text input , Trying to create a value for its text input v-model. Usually , We have to accept a value of prop, then emit A change event to update the data value in the parent component .

We can use useVModel, Take it as an ordinary ref, Instead of using ref And call props.value and update:value. This helps to reduce the number of different grammars we need to remember !

<template>
<div>
<input
type="text"
:value="data"
@input="update"
/>

</div>
</template>

<script>
import { useVModel } from '@vueuse/core'
export default {
props: ['data'],
setup(props, { emit }) {
const data = useVModel(props, 'data', emit)
console.log(data.value) // equal to props.data
data.value = 'name' // equal to emit('update:data', 'name')
const update = (event) => {
data.value = event.target.value
}
return {
data,
update
}
},
}
</script>

Whenever we need to access our values , We just call .value,useVModel From our components props It gives us value . And whenever we change the value of an object ,useVModel The parent component Issue an update event .

Here's a quick example , Explain what the parent component might look like ...

<template>
<div>
<p> {{ data }} </p>
<custom-input
:data="data"
@update:data="data = $event"
/>

</div>
</template>

<script>
import CustomInput from './components/CustomInput.vue'
import { ref } from 'vue'
export default {
components: {
CustomInput,
},
setup () {
const data = ref('hello')
return {
data
}
}
}

It turned out to look like this , Our value in the parent is always in sync with the input in the child .

 picture

Use IntersectionObserver Trace element visibility

In determining whether two elements overlap ,Intersection Observers [2] Very powerful . A good use case is to check whether the element is currently visible in the view .

Essentially , It checks the target element and the root element / The percentage of document intersections . If the percentage exceeds a certain threshold , It calls a callback to determine if the target element is visible .

useIntersectionObserver Provides a simple syntax to use IntersectionObserver API. All we need to do is provide a template for the elements we want to check ref. By default ,IntersectionObserver It's going to be based on the view of the document , The threshold for 0.1—— So when this threshold is going out in any direction , Our intersection observer will be triggered .

The code for this example might look like this : We have a fake paragraph , It's just taking up space in our view , Our goal element , Then there's a print statement , Print the visibility of our elements .

<template>
<p> Is target visible? {{ targetIsVisible }} </p>
<div class="container">
<div class="target" ref="target">
<h1>Hello world</h1>
</div>
</div>
</template>

<script>
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
)
return {
target,
targetIsVisible,
}
},
}
</script>

<style scoped>
.container {
width: 80%;
margin: auto;
background-color: #fafafa;
max-height: 300px;
overflow: scroll;
}
.target {
margin-top: 500px;
background-color: #1abc9c;
color: white;
padding: 20px;
}
</style>

When we run and scroll it , We'll see it updated correctly .

 picture

We can also for Intersection Observer Specify more options , For example, change its root element 、 Margin ( The offset of the root bounding box used to calculate the intersection ) And threshold levels .

const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
{
// root, rootMargin, threshold, window
// full options in the source: https://github.com/vueuse/vueuse/blob/main/packages/core/useIntersectionObserver/index.ts
threshold: 0.5,
}
)

Equally important , This method returns a stop function , We can call this function to stop looking at the intersection . If we just want to track the first time an element is visible on the screen , This is particularly useful .

In this code , once targetIsVisible Set to true, The observer will stop , Even if we scroll away from the target element , Our value will also remain at true.

const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
if (isIntersecting) {
stop()
}
},
)

useTransition Transition between values

useTransition As a whole veuse One of my favorite functions in the library . It allows us to convert values smoothly in one line .

We have a store for ref A digital source and an output that will moderate between different values . for example , Suppose we want to build a counter

 picture

We can do this in three steps :

  • Create our count ref And initialize it to zero
  • Use useTransition establish output  ref( Set duration and conversion type )
  • change count Value
<script setup>
import { ref } from 'vue'
import { useTransition, TransitionPresets } from '@vueuse/core'

const source = ref(0)

const output = useTransition(source, {
duration: 3000,
transition: TransitionPresets.easeOutExpo,
})

source.value = 5000

</script>

then , In our template , We want to show output Value , Because it can smooth transition between different values .

<template>
<h2>
<p> Join over </p>
<p> {{ Math.round(output) }}+ </p>
<p>Developers </p>
</h2>
</template>

<script setup>
import { ref } from 'vue'
import { useTransition, TransitionPresets } from '@vueuse/core'
const source = ref()
const output = useTransition(source, {
duration: 3000,
transition: TransitionPresets.easeOutExpo,
})
source.value = 5000
</script>

This is the result !

 picture

We can also use useTransition To transition the entire array of numbers , This is useful when dealing with position or color . One of the best ways to deal with color is to use a calculated property to RGB Values are formatted with the correct color Syntax .

<template>
<h2 :style="{ color: color } "> COLOR CHANGING </h2>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTransition, TransitionPresets } from '@vueuse/core'
const source = ref([, , ])
const output = useTransition(source, {
duration: 3000,
transition: TransitionPresets.easeOutExpo,
})
const color = computed(() => {
const [r, g, b] = output.value
return `rgb(${r}, ${g}, ${b})`
})
source.value = [255, , 255]
</script>
 picture

Some cool ways to further customize are to use any built-in transition presets or use CSS Slow function to define our own transition .

The last thought

This is definitely not. VueUse A complete guide to , These are just what I found out VueUse Many of the most interesting functions in the library .

I like all the practical features that help speed up development , Because each of them is to solve specific and common use cases .

I'd like to hear how you implement it in your own project VueUse Of . Please leave any comments below .


original text :https://learnvue.co/2021/07/5-vueuse-library-functions-that-can-speed-up-development/
author :Matt Maribojoc

Recent articles

Reference material

[1]

Official documents : https://vueuse.org/functions.html

[2]

Intersection Observers : https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver


版权声明
本文为[Front end full stack developer]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183711939Q.html

Scroll to Top