Share five useful VueUse functions, let's use them together!
Aug 13, 2021 pm 05:39 PMVueUse is an open source project by Anthony Fu. It provides Vue developers with a large number of basic Composition API utility functions for Vue2 and Vue3.
It has dozens of solutions for common developer use cases, such as tracking ref changes, detecting element visibility, simplifying common Vue patterns, keyboard/mouse input, etc. This is a great way to really save development time, because we don't have to add all these standard features ourselves, just use them and use them (thanks again for your efforts).
I like the VueUse library because it really puts developers first when deciding what utilities to provide, and it's a well-maintained library because it keeps up with the current version of Vue.
What are the practical methods of VueUse?
If you want to see a complete list of each utility, it is recommended to read the official documentation. But to summarize, there are 9 types of functions in VueUse.
Animation - includes easy-to-use transitions, timeouts and timing features
Browser - can be used with different Screen controls, clipboard, preferences, and more
Component - Provides shorthand for different component methods
Sensors - Used to monitor different DOM events, input events and network events
State (state) -Manage user state (global, local storage, session storage)
Utility (utility method)--different utility methods, such as getters, conditionals, ref synchronization, etc.
Watch --More advanced observer types, such as pauseable observers, abandoned observers and conditional observers
Others - Different types of functionality for events, WebSockets and Web workers
Install Vueuse into a Vue project
VueUse One of the biggest features is that it is compatible with Vue2 and Vue3 with only one package!
There are two options for installing VueUse: 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>
It is recommended to use NPM because it is easier Understood, but if we use CDN, it may be accessed through window.VueUse.
Using npm, you can get the desired method through deconstruction:
import { useRefHistory } from '@vueuse/core'
useRefHistory to track changes in responsive data
useRefHistory tracks every change made to ref and stores it in an array. This allows us to easily provide undo and redo capabilities to our applications.
Let’s look at an example where we make a text area that can be undone
The first step is to create our basic component without VueUse - using 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>
Next, import useRefHistory, and then extract the history, undo and redo attributes from text through useRefHistory.
import { ref } from 'vue' import { useRefHistory } from '@vueuse/core' const text = ref('') const { history, undo, redo } = useRefHistory(text)
Whenever our ref changes and the history attribute is updated, a listener will be triggered.
In order to see what the bottom layer is doing, we print out the history content. And call the undo and redo functions when the corresponding button is clicked.
- {{ entry }}
There are also different options to add more functionality to this feature. For example, we can drill down into reactive objects and limit the number of history records like this.
const { history, undo, redo } = useRefHistory(text, { deep: true, capacity: 10, })
onClickOutside off modal
onClickOutside detects any click outside an element. In my experience, the most common use case for this feature is closing any modal or popup.
Typically, we want our modal to block the rest of the web page to draw the user's attention and limit errors. However, if they do click outside the modal, we want it to close.
To do this, there are only two steps.
Create a template reference for the element to be detected
Use this template ref to run onClickOutside
This is a simple component that uses onClickOutside popup window.
<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>
useVModel Simplifies v-model binding.
A common use case for Vue developers is to create a custom v-model binding for a component. This also requires that our component accepts a value as a prop. Whenever this value is modified, our component will emit an update event to the parent class.
# The useVModel function simplifies this to just using standard ref syntax. Let's say we have a custom text input and are trying to create a v-model for the value of its text input. Normally, we have to accept a value prop and then emit a change event to update the data value in the parent component.
We can use useVModel and treat it as a normal ref instead of using ref and calling props.value and update:value. This helps reduce the number of different syntaxes 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>
每當(dāng)需要訪問value時,我們只需調(diào)用.value,useVModel將從我們的組件 props 中給我們提供值。而每當(dāng)改變對象的值時,useVModel 會向父組件發(fā)出一個更新事件。
下面是父組件的一個簡單示例
<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 } } }
使用 intersectionobserver 跟蹤元素的可見性
當(dāng)確定兩個元素是否重疊時,useIntersectionObserver 是非常強(qiáng)大的。這方面的一個很好的用例是檢查一個元素在視口中是否當(dāng)前可見。
基本上,它檢查目標(biāo)元素與根元素/文檔相交的百分比。如果這個百分比超過了某個閾值,它就會調(diào)用一個回調(diào),確定目標(biāo)元素是否可見。
useIntersectionObserver提供了一個簡單的語法來使用IntersectionObserver API。我們所需要做的就是為我們想要檢查的元素提供一個模板ref。
默認(rèn)情況下,IntersectionObserver將以文檔的視口為根基,閾值為0.1--所以當(dāng)這個閾值在任何一個方向被越過時,我們的交集觀察器將被觸發(fā)。
示例:我們有一個假的段落,只是在我們的視口中占據(jù)了空間,目標(biāo)元素,然后是一個打印語句,打印我們元素的可見性。
<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>
運(yùn)行后,對應(yīng)的值會更新:
我們還可以為我們的 Intersection Observer 指定更多的選項(xiàng),比如改變它的根元素、邊距(計算交叉點(diǎn)時對根的邊界框的偏移)和閾值水平。
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, } )
同樣重要的是,這個方法返回一個 stop 函數(shù),我們可以調(diào)用這個函數(shù)來停止觀察交叉點(diǎn)。如果我們只想追蹤一個元素在屏幕上第一次可見的時候,這就特別有用。
在這段代碼中,一旦targetIsVisible被設(shè)置為true,observer 就會停止,即使我們滾動離開目標(biāo)元素,我們的值也會保持為 true 。
const { stop } = useIntersectionObserver( target, ([{ isIntersecting }], observerElement) => { targetIsVisible.value = isIntersecting if (isIntersecting) { stop() } }, )
使用 useTransition 做個數(shù)字加載動畫
useTransition是整個VueUse庫中我最喜歡的函數(shù)之一。它允許我們只用一行就能順利地在數(shù)值之間進(jìn)行過渡。
我們可以通過三個步驟來做到這一點(diǎn)。
初始化一個 ref 變量 count ,初始值為 0
使用 useTransition 創(chuàng)建一個變量 output
改變 count 的值
import { ref } from 'vue' import { useTransition, TransitionPresets } from '@vueuse/core' const count = ref(0) const output = useTransition(count , { duration: 3000, transition: TransitionPresets.easeOutExpo, }) count.value = 5000 </script>
然后在 template 中顯示 output 的值:
<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 count = ref(0) const output = useTransition(count, { duration: 3000, transition: TransitionPresets.easeOutExpo, }) count.value = 5000 </script>
我們還可以使用useTransition 轉(zhuǎn)換整個數(shù)字?jǐn)?shù)組。 使用位置或顏色時,這非常有用。 使用顏色的一個很好的技巧是使用計算的屬性將RGB值格式化為正確的顏色語法。
<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}, $)` }) source.value = [255, , 255] </script>
總結(jié)
這不是VueUse的完整指南。這些只是我平常比較常用的函數(shù),還有很多好用的函數(shù),大家可以自行到官網(wǎng)去學(xué)習(xí)使用。
【相關(guān)推薦:《vue.js教程》】
The above is the detailed content of Share five useful VueUse functions, let's use them together!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Backdrop-filter is used to apply visual effects to the content behind the elements. 1. Use backdrop-filter:blur(10px) and other syntax to achieve the frosted glass effect; 2. Supports multiple filter functions such as blur, brightness, contrast, etc. and can be superimposed; 3. It is often used in glass card design, and it is necessary to ensure that the elements overlap with the background; 4. Modern browsers have good support, and @supports can be used to provide downgrade solutions; 5. Avoid excessive blur values and frequent redrawing to optimize performance. This attribute only takes effect when there is content behind the elements.

The style of the link should distinguish different states through pseudo-classes. 1. Use a:link to set the unreached link style, 2. a:visited to set the accessed link, 3. a:hover to set the hover effect, 4. a:active to set the click-time style, 5. a:focus ensures keyboard accessibility, always follow the LVHA order to avoid style conflicts. You can improve usability and accessibility by adding padding, cursor:pointer and retaining or customizing focus outlines. You can also use border-bottom or animation underscore to ensure that the link has a good user experience and accessibility in all states.

User agent stylesheets are the default CSS styles that browsers automatically apply to ensure that HTML elements that have not added custom styles are still basic readable. They affect the initial appearance of the page, but there are differences between browsers, which may lead to inconsistent display. Developers often solve this problem by resetting or standardizing styles. Use the Developer Tools' Compute or Style panel to view the default styles. Common coverage operations include clearing inner and outer margins, modifying link underscores, adjusting title sizes and unifying button styles. Understanding user agent styles can help improve cross-browser consistency and enable precise layout control.

Use the border attribute to set the dashed style to quickly create dotted lines, such as border-top:2pxdashed#000; 2. You can customize the appearance of the dotted line by adjusting the border width, color and style; 3. When applying the dotted line to dividers or inline elements, it is recommended to set height:0 or reset the default style of hr; 4. If you need to accurately control the length and spacing of the dotted line, you should use background-image and linear-gradient to cooperate with linear-gradient, for example, background:linear-gradient(toright, black33%, transparent33%) repe

Define@keyframesbouncewith0%,100%attranslateY(0)and50%attranslateY(-20px)tocreateabasicbounce.2.Applytheanimationtoanelementusinganimation:bounce0.6sease-in-outinfiniteforsmooth,continuousmotion.3.Forrealism,use@keyframesrealistic-bouncewithscale(1.1

To achieve CSS element overlap, you need to use positioning and z-index attributes. 1. Use position and z-index: Set elements to non-static positioning (such as absolute, relative, etc.), and control the stacking order through z-index, the larger the value, the higher the value. 2. Common positioning methods: absolute is used for precise layout, relative is used for relatively offset and overlap adjacent elements, fixed or sticky is used for fixed positioning of suspended layers. 3. Actual example: By setting the parent container position:relative, child element position:absolute and different z-index, the card overlap effect can be achieved.

The best use scenario for CSS will-change attribute is to inform browser elements in advance of possible changes in order to optimize rendering performance, especially for animation or transition effects. ① It should be applied before the animation properties (such as transform, opacity or position) changes; ② Avoid premature use or long-term retention, and should be set before the change occurs and removed after completion; ③ It should only be used for necessary properties rather than using will-change:all; ④ Suitable for scenarios such as large scrolling animations, interactive UI components, and complex SVG/Canvas interfaces; ⑤ Modern browsers can usually optimize automatically, so there is no need to use will-change in all animations. Proper use can improve

Tocenteradivhorizontally,setawidthandusemargin:0auto.2.Forhorizontalandverticalcentering,useFlexboxwithjustify-content:centerandalign-items:center.3.Alternatively,useCSSGridwithplace-items:center.4.Forolderbrowsers,useabsolutepositioningwithtop:50%,l
