VueUse 提供了 200+ 个基本实用程序函数的集合,用于与浏览器、状态、网络、动画、时间等各种 API 进行交互,这些函数可以轻松导入并在 Vue.js 组件中使用。因此,无需……
VueUse 提供了 200+ 个基本实用程序函数的集合,用于与浏览器、状态、网络、动画、时间等各种 API 进行交互,这些函数可以轻松导入并在 Vue.js 组件中使用。因此,无需编写太多代码就可以添加访问本地存储、使用全屏、单击元素外部等功能。只需组合导入,即可使用。
安装
npm i @vueuse/core
用法
// reactive localStorage
<script setup lang="ts">
import { useStorage } from '@vueuse/core'
const state = useStorage('my-store', { hello: 'hi', greeting: 'Hello' })
</script>
上面的代码提供了一种在浏览器的localStorage
或sessionStorage
中存储数据的响应式方法。因此可以实时查看本地存储和会话存储中的更新数据。
//create a draggable element
<script setup lang="ts">
import { ref } from 'vue'
import { useDraggable } from '@vueuse/core'
const el = ref<HTMLElement | null>(null)
// `style` will be a helper computed for `left: ?px; top: ?px;`
const { x, y, style } = useDraggable(el, {
initialValue: { x: 40, y: 40 },
})
</script>
<template>
<div ref="el" :style="style" style="position: fixed">
Drag me! I am at {{x}}, {{y}}
</div>
</template>
上面的代码使el
元素可拖动,并且还提供有关元素移动时 x 轴和 y 轴屏幕位置的实时信息。
//Detects that a target element's visibility.
<div ref="target">
<h1>Hello world</h1>
</div>
<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>
上面的代码中,当链接的元素在屏幕上可见时会触发事件。这是一项非常简便的技术,用于创建一个动画触发器。
VueUse中有很多组合用法,如果你感兴趣,也可以更深入地研究这方面的知识。
插件地址:https://vueuse.org/
还没有评论呢,快来抢沙发~