[Vue] Introducing VueUse

VueUse is an open source collection of composables for Vue 3, and is very well written. It’s a great resource to learn how to write great composables! To use VueUse composables in our application, we can install it in an existing Vue 3 project by running:

npm i @vueuse/core

Now let’s try using a composable from VueUse. First, we’ll look at useTitle, and then we’ll see how useRefHistory works.


Using useTitle

The useTitle composable is fairly straightforward. It let’s you update the page’s title:

<script setup>
import { useTitle } from '@vueuse/core'

const title = useTitle('Green Socks', { titleTemplate: '%s | My Store' })
</script>

<template>
    <h1>Title Composable</h1>
    <input v-model="title" type="text">
</template>

Here is what this produces:

Now let’s look at a slightly more complicated composable that also uses this options object pattern.


useRefHistory

The useRefHistory composable is a bit more interesting. It let’s you track all of the changes made to a ref, allowing you to perform undo and redo operations fairly easily:

import { useRefHistory } from '@vueuse/core'

// Set up the count ref and track it
const count = ref(0);
const { undo } = useRefHistory(count);

// Increment the count
count.value++;

// Log out the count, undo, and log again
console.log(counter.value);
// 1
undo();
console.log(counter.value);
// 0

This composable can take a bunch of different options, we could call it like so:

import { useRefHistory } from '@vueuse/core'

const state = ref({});
const { undo } = useRefHistory(state, {
  deep: true,  // Track changes inside of arrays and objects
  capacity: 15 // Limit how many steps we track
});

If we look at the source code for this composable, we see it uses the exact same object destructuring pattern that useTitle does:

export function useRefHistory(source, options) {
  const {
    deep = false,
    flush = 'pre',
    eventFilter,
  } = options;

// ...
}

However, in this example we only pull out a few values from the options object here at the start.

This is because useRefHistory relies on the useManualRefHistory composable internally. The rest of the options are passed as that composable’s options object later on in the composable:

// ...const manualHistory = useManualRefHistory(
  source,
  {
// Pass along the options object to another composable
    ...options,
    clone: options.clone || deep,
    setSource,
  },
);

// ...

This also shows something I mentioned earlier: composables can use other composables!

 

Bringing it all together

This lesson was the first in our course, “Writing Better Composables”.

We looked at how adding an options object as a parameter can make for much more configurable components. For example, you don’t need to worry about argument ordering or to remember what each argument does, and adding more options to an object is far easier than updating the arguments passed in.

But we didn’t just look at the pattern itself. We also saw how the VueUse composables useTitle and useRefHistory implement this pattern. They do it in slightly different ways, but since this is a simple pattern, there’s not much variation that you can do.

The next lesson in this course looks at how we can accept both refs and regular Javascript values as arguments:

// Works if we give it a ref we already have
const countRef = ref(2);
useCount(countRef);

// Also works if we give it just a number
const countRef = useCount(2);

This adds flexibility, allowing us to use our composables in more situations in our application.

posted @   Zhentiw  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-04 [Docker] Remove all containers and images
2023-02-04 [Docker] Build multi stage image
2022-02-04 [RxJS] Using iif
2020-02-04 [NestJS] NestJs Data Validation with ValidationPipe
2016-02-04 [Unit Testing] Based on input value, spyOn function
2016-02-04 [Cycle.js] Generalizing run() function for more types of sources
2016-02-04 [Redux] Extracting Container Components -- Complete
点击右上角即可分享
微信分享提示