search
HomeWeb Front-endVue.jsSummarize and share some of the best combinations of VueUse, come and collect them for use!

VueUse is an open source project by Anthony Fu that provides Vue developers with a number of basic Composition API utility functions for Vue 2 and Vue 3. This article will share with you some of the best VueUse combinations that I commonly use. I hope it will be helpful to everyone!

Summarize and share some of the best combinations of VueUse, come and collect them for use!

(Learning video sharing: vue video tutorial)

Vueuse has a large number of excellent combinations. But the volume is so large that trying to read them all might miss the point. Here are some useful combinations, they are as follows:

  • onClickOutside

  • useFocusTrap

  • useHead

  • useStorage

  • useVModel

  • ##useImage

  • useDark

1. onClickOutside

Detecting clicks is very simple. But how do you detect when a click occurs outside an element? That's a little trickier. But it's easy to do this using the onClickOutside component in VueUse. The code is as follows:

<script>
import { ref } from &#39;vue&#39;
import { onClickOutside } from &#39;@vueuse/core&#39;

const container = ref(null)
onClickOutside(container, () => alert(&#39;Good. Better to click outside.&#39;))
</script>

<template>
  <div>
    <p>Hey there, here's some text.</p>
    <div>
      <p>Please don't click in here.</p>
    </div>
  </div>
</template>
Create a

ref for the container element you want to track:

const container = ref(null);
Then we use the

ref on the element Attribute turns it into a templateref.

<div>
  <p>Please don't click in here.</p>
</div>
Once we have the

ref of the container, we pass it along with a handler to the onClickOutside combination.

onClickOutside(
  container,
  () => alert('Good. Better to click outside.')
)
This composability is useful for managing windows or drop-down menus. You can close the drop-down menu when the user clicks outside of it.

Modal boxes often exhibit this behavior as well.

Example address: https://stackblitz.com/edit/vue3-script-setup-with-vite-18scsl?file=src/App.vue

2. useFocusTrap

In order to have an accessible application, it is important to manage focus correctly.

There is nothing worse than accidentally adding a tab after a modal and not being able to return focus to the modal. This is what the focus trap does.

Lock the keyboard focus on a specific DOM element. Instead of cycling through the entire page, it cycles through the browser itself. The keyboard focus only cycles through that DOM element.

The following is an example of using VueUse's

useFocusTrap:

<script>
import { ref } from &#39;vue&#39;
import { useFocusTrap } from &#39;@vueuse/integrations/useFocusTrap&#39;

const container = ref(null)
useFocusTrap(container, { immediate: true })
</script>

<template>
  <div>
    <button>Can't click me</button>
    <div>
      <button>Inside the trap</button>
      <button>Can't break out</button>
      <button>Stuck here forever</button>
    </div>
    <button>Can't click me</button>
  </div>
</template>
Set

immediate to true when the page loads , focus will be placed on the container element. Then, it becomes impossible to label outside of that container.

After reaching the third button, clicking the

tab key again will return to the first button.

Just like

onClickOutside, we first set up the template ref for the container.

const container = ref(null)
<div>
  <button>Inside the trap</button>
  <button>Can't break out</button>
  <button>Stuck here forever</button>
</div>
Then we pass this template reference to the

useFocusTrap combination. The

useFocusTrap(container, { immediate: true });

immediate option will automatically set focus to the first focusable element within the container.

Example address: https://stackblitz.com/edit/vue3-script-setup-with-vite-eocc6w?file=src/App.vue

3. useHead

VueUse provides us with a simple way to update the head part of our application - page title, scripts and other content that may be placed here. thing.

The useHead combo requires us to first set up a plugin

import { createApp } from 'vue'
import { createHead } from '@vueuse/head'
import App from './App.vue'

const app = createApp(App)
const head = createHead()

app.use(head)
app.mount('#app')
Once we use this plugin we can update the header section however we want. In this example, we will inject some custom styles on a button.

<script>
import { ref } from &#39;vue&#39;
import { useHead } from &#39;@vueuse/head&#39;

const styles = ref(&#39;&#39;)
useHead({
  // Inject a style tag into the head
  style: [{ children: styles }],
})

const injectStyles = () => {
  styles.value = &#39;button { background: red }&#39;
}
</script>

<template>
  <div>
    <button>Inject new styles</button>
  </div>
</template>
First, we create a

ref to represent the style we want to inject. The default is empty:

const styles = ref('');
Second, set

useHead to Styles are injected into the page.

useHead({
  // Inject a style tag into the head
  style: [{ children: styles }],
})
Then, add methods to inject these styles:

const injectStyles = () => {
  styles.value = 'button { background: red }'
}
Of course, we are not limited to injecting styles. We can add any of these in our

:
  • title

  • meta tags

  • link tags

  • base tag

  • ##style tags
  • script tags
  • html attributes
  • body attributes
Example address: https://stackblitz.com/edit/vue3-script-setup-with-vite-szhedp?file=src/App.vue

4、useStorage

useStorage

is really cool because it will automatically synchronize ref to localstorage, for example: <pre class="brush:php;toolbar:false">&lt;script&gt; import { useStorage } from &amp;#39;@vueuse/core&amp;#39; const input = useStorage(&amp;#39;unique-key&amp;#39;, &amp;#39;Hello, world!&amp;#39;) &lt;/script&gt; &lt;template&gt;   &lt;div&gt;     &lt;input&gt;   &lt;/div&gt; &lt;/template&gt;</pre> <p>第一次加载时, <code>input 显示 'Hello, world!',但最后,它会显示你最后在 input 中输入的内容,因为它被保存在localstorage中。

除了 localstorage,我们也可以指定  sessionstorage:

const input = useStorage('unique-key', 'Hello, world!', sessionStorage)

当然,也可以自己实现存储系统,只要它实现了StorageLike接口。

export interface StorageLike {
  getItem(key: string): string | null
  setItem(key: string, value: string): void
  removeItem(key: string): void
}

5、useVModel

v-model指令是很好的语法糖,使双向数据绑定更容易。

useVModel更进一步,摆脱了一堆没有人真正想写的模板代码。

<script>
import { useVModel } from &#39;@vueuse/core&#39;

const props = defineProps({
  count: Number,
})
const emit = defineEmits([&#39;update:count&#39;])

const count = useVModel(props, &#39;count&#39;, emit)
</script>

<template>
  <div>
    <button>-</button>
    <button>Reset to 0</button>
    <button>+</button>
  </div>
</template>

在这个例子中,我们首先定义了要附加到v-model上的 props:

const props = defineProps({
  count: Number,
})

然后我们发出一个事件,使用v-model的命名惯例update:<propname></propname>:

const emit = defineEmits(['update:count'])

现在,我们可以使用useVModel组合来将 prop和事件绑定到一个ref

const count = useVModel(props, 'count', emit)

每当 prop 发生变化时,这个 count 就会改变。但只要它从这个组件中被改变,它就会发出update:count事件,通过v-model指令触发更新。

我们可以像这样使用这个 Input 组件。

<script>
import { ref } from &#39;vue&#39;
import Input from &#39;./components/Input.vue&#39;

const count = ref(50)
</script>

<template>
  <div>
    <input>
    {{ count }}
  </div>
</template>

这里的count  ref是通过v-model绑定与 Input组件内部的count ref同步的。

事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-ut5ap8?file=src%2FApp.vue

6、useImage

随着时间的推移,web应用中的图像变得越来越漂亮。我们已经有了带有srcset的响应式图像,渐进式加载库,以及只有在图像滚动到视口时才会加载的库。

但你知道吗,我们也可以访问图像本身的加载和错误状态?

我以前主要通过监听每个HTML元素发出的onloadonerror事件来做到这一点,但VueUse给我们提供了一个更简单的方法,那就是useImage组合。

<script>
import { useImage } from &#39;@vueuse/core&#39;

// Change this to a non-existent URL to see the error state
const url = &#39;https://source.unsplash.com/random/400x300&#39;
const { isLoading, error } = useImage(
  {
    src: url,
  },
  {
    // Just to show the loading effect more clearly
    delay: 2000,
  }
)
</script>

<template>
  <div>
    <div></div>
    <div>Couldn't load the image :(</div>
    <img  src="/static/imghwm/default1.png" data-src="url" class="lazy" alt="Summarize and share some of the best combinations of VueUse, come and collect them for use!" >
  </div>
</template>

第一步,通过useImage 设置图片的src:

const { isLoading, error } = useImage({ src: url })

获取它返回的isLoadingerror引用,以便跟踪状态。这个组合在内部使用useAsyncState,因此它返回的值与该组合的值相同。

安排好后,useImage 就会加载我们的图像并将事件处理程序附加到它上面。

我们所要做的就是在我们的模板中使用相同的URL来使用该图片。由于浏览器会重复使用任何缓存的图片,它将重复使用由useImage加载的图片。

<template>
  <div>
    <div></div>
    <div>Couldn't load the image :(</div>
    <img  src="/static/imghwm/default1.png" data-src="url" class="lazy" alt="Summarize and share some of the best combinations of VueUse, come and collect them for use!" >
  </div>
</template>

在这里,我们设置了一个基本的加载和错误状态处理程序。当图片正在加载时,我们显示一个带有动画渐变的占位符。如果有错误,我们显示一个错误信息。否则我们可以渲染图像。

UseImage 还有其他一些很棒的特性!如果想让它成为响应式图像,那么它支持srcsetsizes属性,这些属性在幕后传递给img元素。

如果你想把所有内容都放在模板中,还有一个无渲染组件。它的工作原理与组合的相同:

<template>
    <useimage>
    <template>
            <div></div>
        </template>
    <template>
            Oops!
        </template>
  </useimage>
</template>

事例:https://stackblitz.com/edit/vue3-script-setup-with-vite-d1jsec?file=src%2FApp.vue

7、暗黑模式 useDark

最近,每个网站和应用程序似乎都有暗黑模式。最难的部分是造型的改变。但是一旦你有了这些,来回切换就很简单了。

如果你使用的是Tailwind,你只需要在html元素中添加dark类,就可以在整个页面中启用。

<!-- ... -->

然而,在黑暗模式和光明模式之间切换时,有几件事需要考虑。首先,我们要考虑到用户的系统设置。第二,我们要记住他们是否已经推翻了这个选择。

VueUse的useDark组合性为我们把所有这些东西都包起来。默认情况下,它查看系统设置,但任何变化都会被持久化到localStorage,所以设置会被记住。

<script>
import { useDark, useToggle } from &#39;@vueuse/core&#39;

const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>

<template>
  <div>
    Changes with dark/light mode.

    <button>
            Enable {{ isDark ? 'Light' : 'Dark' }} Mode
        </button>
  </div>
</template>

黑暗模式的样式:

.dark .container {
  background: slategrey;
  color: white;
  border-color: black;
}

.dark button {
  background: lightgrey;
  color: black;
}

.dark body {
  background: darkgrey;
}

如果你没有使用Tailwind,你可以通过传入一个选项对象来完全定制黑暗模式的应用方式。下面是默认的Tailwind:

const isDark = useDark({
  selector: 'html',
  attribute: 'class',
  valueDark: 'dark',
  valueLight: '',
})

也可以提供一个onChanged处理程序,这样你就可以编写任何你需要的Javascript。这两种方法使你可以使它与你已有的任何造型系统一起工作。

Summary

Vueuse has a huge library with great combinations, and we've only covered a small part of it here. I highly recommend you take some time to explore the documentation and see all that is available. This is a great resource that will save you from a lot of boilerplate code and constantly reinventing the wheel.

[Related video tutorial recommendations: vuejs entry tutorial, web front-end entry]

The above is the detailed content of Summarize and share some of the best combinations of VueUse, come and collect them for use!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

How to jump to the div of vueHow to jump to the div of vueApr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools