作者:我只是一個小菜雞
https://juejin.cn/post/7029699344596992031
什麼是 VueUseVueUse 是一個基於 Composition API 的實用函數集合。通俗的來說,這就是一個工具函數包,它可以幫助你快速實現一些常見的功能,免得你自己去寫,解決重複的工作內容。以及進行了基於 Composition API 的封裝。讓你在 vue3 中更加得心應手。
簡單上手安裝 VueUse
npm i @vueuse/core
使用 VueUse
// 導入
import { useMouse, usePreferredDark, useLocalStorage } from @vueuse/core
export default {
setup() {
// tracks mouse position
const { x, y } = useMouse()
// is user prefers dark theme
const isDark = usePreferredDark()
// persist state in localStorage
const store = useLocalStorage(
my-storage ,
{
name: Apple ,
color: red ,
},
)
return { x, y, isDark, store }
}
}
上面從 VueUse 當中導入了三個函數, useMouse, usePreferredDark, useLocalStorage。useMouse 是一個監聽當前滑鼠坐標的一個方法,他會實時的獲取滑鼠的當前的位置。usePreferredDark 是一個判斷用戶是否喜歡深色的方法,他會實時的判斷用戶是否喜歡深色的主題。useLocalStorage 是一個用來持久化數據的方法,他會把數據持久化到本地存儲中。
還有我們熟悉的 「防抖」 和 「節流」import { throttleFilter, debounceFilter, useLocalStorage, useMouse } from @vueuse/core
// 以節流的方式去改變 localStorage 的值
const storage = useLocalStorage( my-key , { foo: bar }, { eventFilter: throttleFilter(1000) })
// 100ms後更新滑鼠的位置
const { x, y } = useMouse({ eventFilter: debounceFilter(100) })
還有還有在 component 中使用的函數
<script setup>
import { ref } from vue
import { onClickOutside } from @vueuse/core
const el = ref()
function close () {
/* ... */
}
onClickOutside(el, close)
</script>
<template>
<section ref="el">
Click Outside of Me
</section>
</template>
上面例子中,使用了 onClickOutside 函數,這個函數會在點擊元素外部時觸發一個回調函數。也就是這裡的 close 函數。在 component 中就是這麼使用
<script setup>
import { OnClickOutside } from @vueuse/components
function close () {
/* ... */
}
</script>
<template>
<OnClickOutside @trigger="close">
<section>
Click Outside of Me
</section>
</OnClickOutside>
</template>
注意⚠️ 這裡的 OnClickOutside 函數是一個組件,不是一個函數。需要package.json 中安裝了 @vueuse/components。
還還有全局狀態共享的函數// store.js
import { createGlobalState, useStorage } from @vueuse/core
export const useGlobalState = createGlobalState(
() => useStorage( vue-use-local-storage ),
)
// component.js
import { useGlobalState } from ./store
export default defineComponent({
setup() {
const state = useGlobalState()
return { state }
},
})
這樣子就是一個簡單的狀態共享了。擴展一下。傳一個參數,就能改變 store 的值了。
還有關於 fetch, 下面👇就是一個簡單的請求了。import { useFetch } from @vueuse/core
const { isFetching, error, data } = useFetch(url)
它還有很多的 option 參數,可以自定義。
// 100ms超時
const { data } = useFetch(url, { timeout: 100 })
// 請求攔截
const { data } = useFetch(url, {
async beforeFetch({ url, options, cancel }) {
const myToken = await getMyToken()
if (!myToken)
cancel()
options.headers = {
...options.headers,
Authorization: `Bearer ${myToken}`,
}
return {
options
}
}
})
// 響應攔截
const { data } = useFetch(url, {
afterFetch(ctx) {
if (ctx.data.title === HxH )
ctx.data.title = Hunter x Hunter // Modifies the resposne data
return ctx
},
})