VueUse
VueUse不是Vue.use,它是為Vue 2和3服務的一套Vue Composition API的常用工具集,是目前世界上Star最高的同類型庫之一。它的初衷就是將一切原本并不支持響應式的JS API變得支持響應式,省去程序員自己寫相關代碼。
VueUse 是一個基于 Composition API 的實用函數集合。通俗的來說,這就是一個工具函數包支持了更好的邏輯分離,它可以幫助你快速實現一些常見的功能,免得你自己去寫,解決重復的工作內容。以及進行了機遇 Composition API 的封裝。
import { 具體方法 } from ‘@vueuse/core’
一些方法的具體用法
- useMouse:監聽當前鼠標坐標的一個方法,他會實時的獲取鼠標的當前的位置
- useLocalStorage:據持久化到本地存儲中
- throttleFilter:節流 throttleFilter(100)
- debounceFilter:防抖 debounceFilter(100)
- OnClickOutside:在點擊元素外部時觸發一個回調函數
- **注意:**這里的 OnClickOutside 函數是一個組件,不是一個函數。需要package.json 中安裝了 @vueuse/components。
- useDraggable
在vue中利用useDraggable實現antDesign中的Modal移動
官方示例:
<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>
?useDraggable 接收兩個參數:target拖拽目標元素。options為可選參數
Component Usage
需要安裝??
npm i @vueuse/core @vueuse/components
<UseDraggable :initialValue="{ x: 10, y: 10 }" v-slot="{ x, y }">Drag me! I am at {{x}}, {{y}}
</UseDraggable>
?本地vue2示例
<UseDraggable
:initialValue="{ x: 10, y: 10 }"
v-slot="{ x, y }"
style="cursor: move; position: fixed; z-index: 999; background: red; padding: 12px;"
><div >Drag me!I am at {{ x }}, {{ y }}</div>
</UseDraggable>import { UseDraggable } from '@vueuse/components'components: {UseDraggable},data 定義 x y
?
其他具體可參考官方文檔 :VueUse