VueUse常用功能记录

数据

useAsyncState

响应式获取异步状态。不会阻塞setup 函数,在promise完成后,将自动触发

useAsyncState | VueUse

javascript
import axios from 'axios'
import { useAsyncState } from '@vueuse/core'

const { state, isReady, isLoading } = useAsyncState(
  axios
    .get('https://jsonplaceholder.typicode.com/todos/1')
    .then(t => t.data),
  { id: null },
)

useStorage

响应式 LocalStorage/SessionStorage

useStorage | VueUse

javascript
import { useStorage } from '@vueuse/core'

// bind object
const state = useStorage('my-store', { hello: 'hi', greeting: 'Hello' })

// bind boolean
const flag = useStorage('my-flag', true) // returns Ref<boolean>

// bind number
const count = useStorage('my-count', 0) // returns Ref<number>

// bind string with SessionStorage
const id = useStorage('my-id', 'some-string-id', sessionStorage) // returns Ref<string>

// delete data from storage
state.value = null

DOM

useDraggable

使元素可拖拽

useDraggable | VueUse

html
<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>

该函数还通过@vueuse/components提供了一个无渲染的组件版本。

html
<UseDraggable :initialValue="{ x: 10, y: 10 }" v-slot="{ x, y }">
  Drag me! I am at {{x}}, {{y}}
</UseDraggable>

<UseDraggable storage-key="vueuse-draggable" storage-type="session">
  Refresh the page and I am still in the same position!
</UseDraggable>

useDropZone

创建一个可以放置文件的区域。

useDropZone | VueUse

html
<script setup lang="ts">
import { useDropZone } from '@vueuse/core'

const dropZoneRef = ref<HTMLDivElement>()

function onDrop(files: File[] | null) {
  // called when files are dropped on zone
}

const { isOverDropZone } = useDropZone(dropZoneRef, onDrop)
</script>

<template>
  <div ref="dropZoneRef">
    Drop files here
  </div>
</template>

useElementBounding

让HTML元素的bounding box 响应式

useElementBounding | VueUse

html
<template>
  <div ref="el" />
</template>

<script setup>
import { ref } from 'vue'
import { useElementBounding } from '@vueuse/core'

const el = ref(null)

const { x, y, top, right, bottom, left, width, height } = useElementBounding(el)
</script>

该函数还通过@vueuse/components提供了一个无渲染的组件版本

html
<UseElementBounding v-slot="{ width, height }">
  Width: {{ width }}
  Height: {{ height }}
</UseElementBounding>