VueUse 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>
每当需要访问value时,我们只需调用.value,useVModel将从我们的组件 props 中给我们提供值。而每当改变对象的值时,useVModel 会向父组件发出一个更新事件。
下面是父组件的一个简单示例
<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 跟踪元素的可见性
当确定两个元素是否重叠时,useIntersectionObserver 是非常强大的。这方面的一个很好的用例是检查一个元素在视口中是否当前可见。
基本上,它检查目标元素与根元素/文档相交的百分比。如果这个百分比超过了某个阈值,它就会调用一个回调,确定目标元素是否可见。
useIntersectionObserver提供了一个简单的语法来使用IntersectionObserver API。我们所需要做的就是为我们想要检查的元素提供一个模板ref。
默认情况下,IntersectionObserver将以文档的视口为根基,阈值为0.1--所以当这个阈值在任何一个方向被越过时,我们的交集观察器将被触发。
示例:我们有一个假的段落,只是在我们的视口中占据了空间,目标元素,然后是一个打印语句,打印我们元素的可见性。
<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>
运行后,对应的值会更新:
我们还可以为我们的 Intersection Observer 指定更多的选项,比如改变它的根元素、边距(计算交叉点时对根的边界框的偏移)和阈值水平。
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 函数,我们可以调用这个函数来停止观察交叉点。如果我们只想追踪一个元素在屏幕上第一次可见的时候,这就特别有用。
在这段代码中,一旦targetIsVisible被设置为true,observer 就会停止,即使我们滚动离开目标元素,我们的值也会保持为 true 。
const { stop } = useIntersectionObserver( target, ([{ isIntersecting }], observerElement) => { targetIsVisible.value = isIntersecting if (isIntersecting) { stop() } }, )
使用 useTransition 做个数字加载动画
useTransition是整个VueUse库中我最喜欢的函数之一。它允许我们只用一行就能顺利地在数值之间进行过渡。
我们可以通过三个步骤来做到这一点。
初始化一个 ref 变量 count ,初始值为 0
使用 useTransition 创建一个变量 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 转换整个数字数组。 使用位置或颜色时,这非常有用。 使用颜色的一个很好的技巧是使用计算的属性将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}, ${b})` }) source.value = [255, , 255] </script>
总结
这不是VueUse的完整指南。这些只是我平常比较常用的函数,还有很多好用的函数,大家可以自行到官网去学习使用。
【相关推荐:《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!