前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >时隔这么长时间,我把常用的功能整理好了,再来感受VueUse工具库的优雅吧~

时隔这么长时间,我把常用的功能整理好了,再来感受VueUse工具库的优雅吧~

作者头像
用户9078190
发布2022-10-28 19:07:47
2.8K0
发布2022-10-28 19:07:47
举报
文章被收录于专栏:知码前端

01

前言

前段时间我曾经写过一篇文章介绍了一个 VueUse 这个工具库,那个时候只是刚开始用,没有深入了解。经过这么长时间的使用,现在现来谈一下使用感受,体验一下VueUse之美。

02

VueUse简介

VueUse是一个工具库,里面包含了大量的基于 CompositionAPI的方法。所以在使用之前要对CompositionAPI是什么有一个了解,这样才能更好的去使用它。

简单的来说,这个工具库里面有很多的函数,这些函数都是开箱即用的。

并且在4.0之后,也同样支持Vue2和Vue3两个版本。

github地址:

https://github.com/vueuse/vueuse

官方文档地址:

https://vueuse.org

安装起来也非常的方便:

代码语言:javascript
复制
npm i @vueuse/core

在VueUse中,绝大多数的工具函数都会返回一个可 refs 的对象,你可以使用 ES6的对象解构语法去获取你需要的数据,如下:

代码语言:javascript
复制
import { useMouse } from '@vueuse/core'

// "x" and "y" are refs
const { x, y } = useMouse()

console.log(x.value)

const mouse = useMouse()

console.log(mouse.x.value)

如果你更喜欢用对象风格的属性,你可以把那个refs对象用reactive方法解析一下,如:

代码语言:javascript
复制
import { reactive } from 'vue'
import { useMouse } from '@vueuse/core'

const mouse = reactive(useMouse())

// "x" and "y" will be auto unwrapped, no `.value` needed
console.log(mouse.x)

不仅如此,VueUse还提供了 Componets的使用方式,真可谓是非常的方便,如下:

代码语言:javascript
复制
<script setup>
import { OnClickOutside } from '@vueuse/components'

function close () {
  /* ... */
}
</script>
<template>
  <OnClickOutside @trigger="close">
    <div>
      Click Outside of Me
    </div>
  </OnClickOutside>
</template>

先介绍这么多,总结一句话就是 VueUse的方法可以以 useXXXX的方式使用,也可以用Comoponets的形式使用。更多的介绍可以去官网查看详细的说明

03

常用功能介绍

VueUse的功能是很强大的,包含了各个方面,我们平时开发可能用不了这么多功能,所以我们重点说一下几个常用的功能。

浏览器相关

1、useClipboard

2、usefavicon

3、useFullscreen

4、useScriptTag

5、useStyleTag

6、useTitle

传感器相关

1、useNetwork

2、useScroll

3、useSwipe

动画相关

1、useInterval

2、useIntervalFn

3、useNow

4、useTimeout

状态管理

1、useLocalStorage

2、useSessionStorage

3、useStorage

元素相关

1、useDraggable - make elements draggable

2.useElementBounding - reactive bounding box of an HTML element

3、useElementSize - reactive size of an HTML element

4、useElementVisibility - tracks the visibility of an element within the viewport

5、useWindowScroll - reactive window scroll

6、useWindowSize - reactive window size

常用工具

1、useBase64 - reactive base64 transforming

2、useCounter - basic counter with utility functions

3、useDateFormat - get the formatted date according to the string of tokens passed in

4、useDebounceFn - debounce execution of a function

5、useEventBus - a basic event bus

6、useThrottleFn - throttle execution of a function

7、useToggle - a boolean switcher with utility functions

个人感觉大体的常功能应该就这么多,当然,VueUse还有很多很多的工具函数,大家可以去官网查看文档。

03

源码分析

下面我们以 useClipboard 为例分析一下源码,看看背后到底是怎么做的 先来看一下源码:

代码语言:javascript
复制
function useClipboard(options = {}) {
  const {
    navigator = defaultNavigator,
    read = false,
    source,
    copiedDuring = 1500
  } = options;
  const events = ["copy", "cut"];
  const isSupported = Boolean(navigator && "clipboard" in navigator);
  const text = vueDemi.ref("");
  const copied = vueDemi.ref(false);
  const timeout = shared.useTimeoutFn(() => copied.value = false, copiedDuring);
  function updateText() {
    navigator.clipboard.readText().then((value) => {
      text.value = value;
    });
  }
  if (isSupported && read) {
    for (const event of events)
      useEventListener(event, updateText);
  }
  async function copy(value = vueDemi.unref(source)) {
    if (isSupported && value != null) {
      await navigator.clipboard.writeText(value);
      text.value = value;
      copied.value = true;
      timeout.start();
    }
  }
  return {
    isSupported,
    text,
    copied,
    copy
  };
}

用法如下:

代码语言:javascript
复制
import { useClipboard } from '@vueuse/core'

const source = ref('Hello')
const { text, copy, copied, isSupported } = useClipboard({ source })

读过程

代码语言:javascript
复制
  if (isSupported && read) {
    for (const event of events)
      useEventListener(event, updateText);
  }

如果浏览器支持的话,会监听 `cut` 和 `copy` 两个事件。如果有对应的事件发生,就会从navigator.clipborad中读取复制的内容,然后再赋值给 text 变量。

这样就可以通过 text 暴露出去,我们就可拿到了复制的内容。

写过程

不过有时候我们想在点击某个按钮的时候进行复制操作,同样 这个工具方法也提供了一个 copy 方法供我们使用,让我们在点击的时候进行操作,如下:

代码语言:javascript
复制
<button @click='copy()'>
  <!-- by default, `copied` will be reset in 1.5s -->
  <span v-if='!copied'>Copy</span>
  <span v-else>Copied!</span>
</button>

当执行 copy操作时候,会往navigator.clipboard中写入我们传入的数据。同时这个工具还提供了一个 标志位,是否复制成功。而且在一定的时间后会把这个标识还原到最初的状态。

从这个简单的方法我们可以自由的使用 clipboard的粘贴复制功能。最重要的是短短的一个方法调用就可实现这两个功能,可以说真的很强大。

VueUse的强大之处还有很多很多,github近9K的star 足以说明人们对他的喜欢。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-03-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 知码前端 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • VueUse简介
  • 常用功能介绍
  • 源码分析
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档