VueUse中的这五个函数,也太好用了吧

开发 前端
VueUse 是 Anthony Fu 大佬的一个开源项目,它为Vue的开发者提供了大量用于 Vue2 和Vue3 的基本 Composition API 实用工具函数。

[[416807]]

VueUse 是 Anthony Fu 大佬的一个开源项目,它为Vue的开发者提供了大量用于 Vue2 和Vue3 的基本 Composition API 实用工具函数。

它有几十个用于常见开发人员用例的解决方案,如跟踪ref更改,检测元素可见性,简化常见Vue模式,键盘/鼠标输入等。 这是真正节省开发时间的好方法,因为我们不必自己亲手添加所有这些标准功能,拿来主义,用就对了(再次感谢大佬的付出)。

我喜欢VueUse库,因为它在决定提供哪些实用工具时真正把开发者放在第一位,而且它是一个维护良好的库,因为它与Vue的当前版本保持同步。

VueUse 有哪些实用方法?

如果你想看到每一个实用程序的完整列表,建议去看看官方文档。但总结一下,VueUse 中有9种类型的函数。

  • Animation(动画) - 包含易于使用的过渡、超时和计时功能
  • Browser (浏览器) - 可以用于不同的屏幕控件、剪贴板、首选项等等
  • Component (组件) - 为不同的组件方法提供简写
  • Sensors (传感器)- 用来监听不同的DOM事件、输入事件和网络事件
  • State (状态) - 管理用户状态(全局,本地存储,会话存储)
  • Utility (实用方法)--不同的实用方法,如getters、conditionals、ref synchronization等。
  • Watch --更高级的观察器类型,如可暂停的观察器、放弃的观察器和条件观察器
  • 其它 - 事件、WebSockets和 Web workers 的不同类型的功能

将 Vueuse 安装到 Vue 项目中

VueUse 的最大特点之一是,它只用一个包就能兼容 Vue2 和 Vue3!

安装VueUse有两种选择:npm或 CDN

  1. npm i @vueuse/core # yarn add @vueuse/core 
  1. <script src="https://unpkg.com/@vueuse/shared"></script> 
  2. <script src="https://unpkg.com/@vueuse/core"></script> 

推荐使用NPM,因为它更容易理解,但如果我们使用CDN, 可能通过 window.VueUse 来访问。

使用 npm,可以通过解构的方式来获得想要的方法:

  1. import { useRefHistory } from '@vueuse/core' 

useRefHistory 跟踪响应式数据的变化

useRefHistory跟踪对 ref 所做的每一个改变,并将其存储在一个数组中。这样我们能够轻松为应用程序提供撤销和重做功能。

来看一个示例,在该示例中,我们做一个能够撤销的文本区域

第一步是在没有 VueUse 的情况下创建我们的基本组件--使用ref、textarea、以及用于撤销和重做的按钮。

  1. <template> 
  2.   <p>  
  3.     <button> Undo </button> 
  4.     <button> Redo </button> 
  5.   </p> 
  6.   <textarea v-model="text"/> 
  7. </template> 
  8.  
  9. <script setup> 
  10. import { ref } from 'vue' 
  11. const text = ref(''
  12. </script> 
  13.  
  14. <style scoped> 
  15.   button { 
  16.     border: none; 
  17.     outline: none; 
  18.     margin-right: 10px; 
  19.     background-color: #2ecc71; 
  20.     color: white; 
  21.     padding: 5px 10px;; 
  22.   } 
  23. </style> 

接着,导入useRefHistory,然后通过 useRefHistory从 text 中提取history、undo和redo属性。

  1. import { ref } from 'vue' 
  2. import { useRefHistory } from '@vueuse/core' 
  3.  
  4. const text = ref(''
  5. const { history, undo, redo } = useRefHistory(text) 

每当我们的ref发生变化,更新history属性时,就会触发一个监听器。

为了看看底层做了什么,我们把 history 内容打印出来。并在单击相应按钮时调用 undo 和redo函数。

  1. <template> 
  2.   <p>  
  3.     <button @click="undo"> Undo </button> 
  4.     <button @click="redo"> Redo </button> 
  5.   </p> 
  6.   <textarea v-model="text"/> 
  7.   <ul> 
  8.     <li v-for="entry in history" :key="entry.timestamp"
  9.       {{ entry }} 
  10.     </li> 
  11.   </ul> 
  12. </template> 
  13.  
  14. <script setup> 
  15. import { ref } from 'vue' 
  16. import { useRefHistory } from '@vueuse/core' 
  17. const text = ref(''
  18. const { history, undo, redo } = useRefHistory(text) 
  19. </script> 
  20.  
  21. <style scoped> 
  22.   button { 
  23.     border: none; 
  24.     outline: none; 
  25.     margin-right: 10px; 
  26.     background-color: #2ecc71; 
  27.     color: white; 
  28.     padding: 5px 10px;; 
  29.   } 
  30. </style> 

直接,跑起来,效果如下:

VueUse中的这5个函数,也太好用了吧

还有不同的选项,为这个功能增加更多的功能。例如,我们可以深入追踪 reactive 对象,并像这样限制 history 记录的数量。

  1. const { history, undo, redo } = useRefHistory(text, { 
  2.   deep: true
  3.   capacity: 10, 
  4. }) 

onClickOutside 关闭 modal

onClickOutside 检测在一个元素之外的任何点击。根据我的经验,这个功能最常见的使用情况是关闭任何模态或弹出窗口。

通常,我们希望我们的模态屏蔽网页的其余部分,以吸引用户的注意和限制错误。然而,如果他们确实点击了模态之外,我们希望它关闭。

要做到这一点,只有两个步骤。

  • 为要检测的元素创建一个模板引用
  • 使用这个模板ref运行onClickOutside

这是一个简单的组件,使用onClickOutside弹出窗口。

  1. <template> 
  2.   <button @click="open = true"Open Popup </button> 
  3.   <div class="popup" v-if='open'
  4.     <div class="popup-content" ref="popup"
  5.       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? 
  6.     </div> 
  7.   </div> 
  8. </template> 
  9.  
  10. <script setup> 
  11. import { ref } from 'vue' 
  12. import { onClickOutside } from '@vueuse/core' 
  13. const open = ref(false) // state of our popup 
  14. const popup = ref() // template ref 
  15. // whenever our popup exists, and we click anything BUT it 
  16. onClickOutside(popup, () => { 
  17.   open.value  = false 
  18. }) 
  19. </script> 
  20.  
  21. <style scoped> 
  22.   button { 
  23.     border: none; 
  24.     outline: none; 
  25.     margin-right: 10px; 
  26.     background-color: #2ecc71; 
  27.     color: white; 
  28.     padding: 5px 10px;; 
  29.   } 
  30.   .popup { 
  31.     position: fixed; 
  32.     top: ; 
  33.     left: ; 
  34.     width: 100vw; 
  35.     height: 100vh; 
  36.     display: flex; 
  37.     align-items: center; 
  38.     justify-content: center; 
  39.     background: rgba(, , , 0.1); 
  40.   } 
  41.   .popup-content { 
  42.     min-width: 300px; 
  43.     padding: 20px; 
  44.     width: 30%; 
  45.     background: #fff; 
  46.   } 
  47. </style 

结果是这样的,我们可以用我们的按钮打开弹出窗口,然后在弹出内容窗口外单击关闭它。

VueUse中的这5个函数,也太好用了吧

useVModel 简化 v-model 的绑定。

Vue开发者的一个常见用例是为一个组件创建一个自定义的v-model绑定。这也要求我们的组件接受一个 value 作为 prop,每当这个 value 被修改,我们的组件就会向父类发出一个 update 事件。

useVModel函数将其简化为只使用标准的ref语法。假设我们有一个自定义的文本输入,试图为其文本输入的值创建一个v-model。通常情况下,我们必须接受一个 value的 prop,然后发出一个 change事件来更新父组件中的数据值。

我们可以使用useVModel,把它当作一个普通的ref,而不是使用ref并调用props.value和update:value。这有助于减少我们需要记住的不同语法的数量!

  1. <template> 
  2.     <div> 
  3.         <input  
  4.             type="text"  
  5.             :value="data" 
  6.             @input="update" 
  7.         /> 
  8.     </div> 
  9. </template> 
  10.  
  11. <script> 
  12. import { useVModel } from '@vueuse/core' 
  13. export default { 
  14.   props: ['data'], 
  15.   setup(props, { emit }) { 
  16.     const data = useVModel(props, 'data', emit) 
  17.     console.log(data.value) // equal to props.data 
  18.     data.value = 'name' // equal to emit('update:data''name'
  19.     const update = (event) => { 
  20.         data.value = event.target.value 
  21.     } 
  22.     return { 
  23.         data, 
  24.         update 
  25.     } 
  26.   }, 
  27. </script> 

每当需要访问value时,我们只需调用.value,useVModel将从我们的组件 props 中给我们提供值。而每当改变对象的值时,useVModel 会向父组件发出一个更新事件。

下面是父组件的一个简单示例

  1. <template> 
  2.   <div> 
  3.     <p> {{ data }} </p> 
  4.     <custom-input  
  5.       :data="data"  
  6.       @update:data="data = $event" 
  7.     /> 
  8.   </div> 
  9. </template> 
  10.  
  11. <script> 
  12. import CustomInput from './components/CustomInput.vue' 
  13. import { ref } from 'vue' 
  14. export default { 
  15.   components: { 
  16.     CustomInput, 
  17.   }, 
  18.   setup () { 
  19.     const data = ref('hello'
  20.     return { 
  21.       data 
  22.     } 
  23.   } 

运行结果如下,父方的值总是与子方的输入保持同步:

VueUse中的这5个函数,也太好用了吧

使用 intersectionobserver 跟踪元素的可见性

当确定两个元素是否重叠时,useIntersectionObserver 是非常强大的。这方面的一个很好的用例是检查一个元素在视口中是否当前可见。

基本上,它检查目标元素与根元素/文档相交的百分比。如果这个百分比超过了某个阈值,它就会调用一个回调,确定目标元素是否可见。

useIntersectionObserver提供了一个简单的语法来使用IntersectionObserver API。我们所需要做的就是为我们想要检查的元素提供一个模板ref。

默认情况下,IntersectionObserver将以文档的视口为根基,阈值为0.1--所以当这个阈值在任何一个方向被越过时,我们的交集观察器将被触发。

示例:我们有一个假的段落,只是在我们的视口中占据了空间,目标元素,然后是一个打印语句,打印我们元素的可见性。

  1. <template> 
  2.   <p> Is target visible? {{ targetIsVisible }} </p> 
  3.   <div class="container"
  4.     <div class="target" ref="target"
  5.       <h1>Hello world</h1> 
  6.     </div> 
  7.   </div> 
  8. </template> 
  9.  
  10. <script> 
  11. import { ref } from 'vue' 
  12. import { useIntersectionObserver } from '@vueuse/core' 
  13. export default { 
  14.   setup() { 
  15.     const target = ref(null
  16.     const targetIsVisible = ref(false
  17.     const { stop } = useIntersectionObserver( 
  18.       target, 
  19.       ([{ isIntersecting }], observerElement) => { 
  20.         targetIsVisible.value = isIntersecting 
  21.       }, 
  22.     ) 
  23.     return { 
  24.       target, 
  25.       targetIsVisible, 
  26.     } 
  27.   }, 
  28. </script> 
  29.  
  30. <style scoped> 
  31. .container { 
  32.   width: 80%; 
  33.   margin:  auto; 
  34.   background-color: #fafafa; 
  35.   max-height: 300px; 
  36.   overflow: scroll
  37. .target { 
  38.   margin-top: 500px; 
  39.   background-color: #1abc9c; 
  40.   color: white; 
  41.   padding: 20px; 
  42. </style> 

运行后,对应的值会更新:

VueUse中的这5个函数,也太好用了吧

我们还可以为我们的 Intersection Observer 指定更多的选项,比如改变它的根元素、边距(计算交叉点时对根的边界框的偏移)和阈值水平。

  1. const { stop } = useIntersectionObserver( 
  2.       target, 
  3.       ([{ isIntersecting }], observerElement) => { 
  4.         targetIsVisible.value = isIntersecting 
  5.       }, 
  6.       { 
  7.         // root, rootMargin, threshold, window 
  8.         // full options in the source: https://github.com/vueuse/vueuse/blob/main/packages/core/useIntersectionObserver/index.ts 
  9.         threshold: 0.5, 
  10.       } 

同样重要的是,这个方法返回一个 stop 函数,我们可以调用这个函数来停止观察交叉点。如果我们只想追踪一个元素在屏幕上第一次可见的时候,这就特别有用。

在这段代码中,一旦targetIsVisible被设置为true,observer 就会停止,即使我们滚动离开目标元素,我们的值也会保持为 true 。

  1. const { stop } = useIntersectionObserver( 
  2.       target, 
  3.       ([{ isIntersecting }], observerElement) => { 
  4.         targetIsVisible.value = isIntersecting 
  5.         if (isIntersecting) { 
  6.           stop() 
  7.         } 
  8.       }, 
  9.     ) 

使用 useTransition 做个数字加载动画

useTransition是整个VueUse库中我最喜欢的函数之一。它允许我们只用一行就能顺利地在数值之间进行过渡。

如果使用 useTransition 做一个下面这样的效果,要怎么做呢?

VueUse中的这5个函数,也太好用了吧

我们可以通过三个步骤来做到这一点。

  • 初始化一个 ref 变量 count ,初始值为 0
  • 使用 useTransition 创建一个变量 output
  • 改变 count 的值
  1. import { ref } from 'vue' 
  2. import { useTransition, TransitionPresets } from '@vueuse/core' 
  3.  
  4. const count = ref(0) 
  5.  
  6. const output = useTransition(count , { 
  7.   duration: 3000, 
  8.   transition: TransitionPresets.easeOutExpo, 
  9. }) 
  10.  
  11. count.value = 5000 
  12.  
  13. </script> 

然后在 template 中显示 output 的值:

  1. <template> 
  2.   <h2>  
  3.     <p> Join over </p> 
  4.     <p> {{ Math.round(output) }}+ </p> 
  5.     <p>Developers </p> 
  6.   </h2> 
  7. </template> 
  8.  
  9. <script setup> 
  10. import { ref } from 'vue' 
  11. import { useTransition, TransitionPresets } from '@vueuse/core' 
  12. const count = ref(0) 
  13. const output = useTransition(count, { 
  14.   duration: 3000, 
  15.   transition: TransitionPresets.easeOutExpo, 
  16. }) 
  17. count.value = 5000 
  18. </script> 

运行结果:

VueUse中的这5个函数,也太好用了吧

我们还可以使用useTransition 转换整个数字数组。 使用位置或颜色时,这非常有用。 使用颜色的一个很好的技巧是使用计算的属性将RGB值格式化为正确的颜色语法。

  1. <template> 
  2.   <h2 :style="{ color: color } "> COLOR CHANGING </h2> 
  3. </template> 
  4.  
  5. <script setup> 
  6. import { ref, computed } from 'vue' 
  7. import { useTransition, TransitionPresets } from '@vueuse/core' 
  8. const source = ref([, , ]) 
  9. const output = useTransition(source, { 
  10.   duration: 3000, 
  11.   transition: TransitionPresets.easeOutExpo, 
  12. }) 
  13. const color = computed(() => { 
  14.   const [r, g, b] = output.value 
  15.   return `rgb(${r}, ${g}, ${b})` 
  16. }) 
  17. source.value = [255, , 255] 
  18. </script> 
VueUse中的这5个函数,也太好用了吧

总结

这不是VueUse的完整指南。这些只是我平常比较常用的函数,还有很多好用的函数,大家可以自行到官网去学习使用。

作者:Matt Maribojoc 译者:前端小智 来源:medium

原文:https://learvue.co/2021/07/5-vueuse-library-functions-that-can-speed-up-development/

 

责任编辑:姜华 来源: 今日头条
相关推荐

2022-05-31 09:42:49

工具编辑器

2020-06-18 10:02:25

Python 开发编程语言

2020-11-10 06:11:59

工具软件代码

2021-03-18 10:12:54

JavaCompletable字符串

2021-07-27 18:02:01

VueUse 函数开发

2022-07-14 08:36:28

NacosApollo长轮询

2021-04-22 09:56:32

MYSQL开发数据库

2022-08-01 07:02:06

SpringEasyExcel场景

2020-06-23 15:58:42

心电图

2021-03-19 09:48:10

Jupyter Not插件Python

2020-12-29 10:45:55

开发设计代码

2022-09-06 10:52:04

正则库HumrePython

2022-07-25 06:42:24

分布式锁Redis

2021-09-10 10:15:24

Python人脸识别AI

2022-05-11 14:43:37

WindowsPython服务器

2021-03-02 20:42:20

实战策略

2022-06-28 07:14:23

WizTree磁盘文件清理

2023-03-31 08:22:48

javassitcglibAOP
点赞
收藏

51CTO技术栈公众号