Vue 新玩具 VueUse

2021-12-23 小生方勤


作者:我只是一個小菜雞

https://juejin.cn/post/7029699344596992031

什麼是 VueUse

VueUse 是一個基於 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
},
})

相關焦點

  • Vue新玩具VueUse
    簡單上手安裝 VueUsenpm i @vueuse/core使用 VueUse// 導入import { useMouse, usePreferredDark, useLocalStorage } from '@vueuse/core'export default { setup() {
  • 【Vuejs】1160- Vue 的新玩具 VueUse
    簡單上手安裝 VueUsenpm i @vueuse/core使用 VueUse// 導入import { useMouse, usePreferredDark, useLocalStorage } from '@vueuse/core'export default { setup() {
  • 5 個可以加速開發的 VueUse 函數庫
    對於NPM的安裝,所有的功能都可以通過使用標準的對象重構從 @vueuse/core 中導入,像這樣訪問。import { useRefHistory } from 『@vueuse/core』好了,現在我們已經安裝了VueUse,讓我們在應用程式中使用它!
  • 5個讓你提高工作效率的 VueUse 庫函數
    英文 | https://learnvue.co/2021/07/5-vueuse-library-functions-that-can-speed-up-development
  • 使用Vue CLI腳手架搭建Vue基礎環境
    3.Vue CLI三種模式默認使用的模式development 模式用於 vue-cli-service serveproduction 模式用於 vue-cli-service build 和 vue-cli-service test:e2etest 模式用於 vue-cli-service test:unit設置模式模式不同於
  • Vue入門10 vue+elementUI
    以英語為例,在main.js中:import Vue from 'vue'import ElementUI from 'element-ui'import locale from 'element-ui/lib/locale/lang/en'Vue.use(ElementUI, { locale })12.1、創建工程
  • Vue全家桶&vue-router原理
    原理 Vue全家桶:vue + vue-router(路由)+ vuex(狀態管理)+ axios(請求)本次主要分析並實現簡版vue-router,從源碼中學習借鑑,更好的理解源碼vue-routerVue Router 是 Vue.js 官⽅的路由管理器。
  • Vue3.0新特性
    自定義函數--hooks函數Teleport - 瞬移組件的位置Suspense - 異步加載組件的新福音全局API的修改和優化更多的誓言性特性更好的Typescript 支持vue3.0源碼就是ts寫的為什麼要有vue3.0?
  • Vue.use 經歷了什麼?
    如果每引入一個組件,再註冊一下,明顯加大了開發的工作量,所以我們需要讓每一個 Vue 都具備這個插件功能,因此我們首選 Vue.use 這個 Vue 的 API。Vue.use官方解說地址:https://cn.vuejs.org/v2/api/#Vue-useVue.use 它是一個函數。
  • @vue/composition-api 與 Vue3 的前生今世
    @vue/compositions-api 是 Vue2 的一個插件,需通過 Vue.use() 進行調用。❞好處是:相同組件邏輯下,原來的 options 形式實現與新的 composition-api 實現代碼結構對比:代碼對比為什麼會有 @vue/compositions-api為了抹平 compositions-api 語法和
  • vue高級進階系列——用typescript玩轉vue和vuex
    本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫用過vue的朋友大概對vuex也不陌生,vuex的官方解釋是專為 Vue.js 應用程式開發的狀態管理模式。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
  • Vue-使用vue-video-player組件
    在實際開發過程中會有添加視頻的需求在vue項目中添加視頻可以使用vue-video-player組件來實現實現步驟:1.安裝在控制臺輸入: npm install vue-video-player –s
  • Vue3 的 7 種和 Vue2 的 12 種組件通信,值得收藏
    // Child.vue<script setup>    // 方法一 不適用於Vue3.2版本,該版本 useContext()已廢棄    import { useContext } from "vue"    const ctx = useContext()    // 對外暴露屬性方法等都可以
  • Vue.js系列之vue-router(上)(3)
    說明:我們項目現在用的是:vue2.0 + vue-cli + webpack + vue-router2.0 + vue-resource1.0.3
  • Webpack 案例 ——vue-loader 原理分析
    ],  },};轉換之後生成 6 個 rule,按定義的順序分別為:針對 xx.vue&vue 格式路徑生效的規則,只用了 Vue-loader 的 pitcher 作為 loader被複製的 css 處理規則,use 數組與開發者定義的規則相同被複製的 js 處理規則,use 數組也跟開發者定義的規則相同開發者原始定義的
  • Vue3.0——生命周期講解
    而在Vue3.0中,Vue2.x Options API形式的生命周期鉤子函數和新的Composition API都可以使用,來看個示例代碼就明白了:整體代碼如下:const { createComponent, createApp, reactive } = Vueconst Counter = { props
  • Vue3.0七大亮點
    render階段的靜態提升(render階段指生成虛擬dom樹的階段)在vue2中,一旦檢查到數據變化,就會re-render組件,所有的vnode都會重新創建一遍,形成新的vdom樹。import useCounter from './counter'import useTodo from '.
  • 搭建 Vue CLI 4.x + Webpack5 + Vue 3.x 移動端框架
    組合式API訪問 State 和 Getter為了訪問 state 和 getter,需要創建 computed 引用以保留響應性import { computed } from 'vue'import { useStore } from 'vuex'export
  • Vue.js系列之vue-resource(6)
    說明:我們項目現在用的是:vue2.0 + vue-cli + webpack + vue-router2.0 +
  • Vue-Router源碼學習之index.js(vue-router類)
    正文vue-router類裡面都做了什麼?首先我們說一下vue-router最核心的內容之一:解析:mode我們知到vue-router的路由有兩種方式,一種是#錨點性的,第二種是和正常路徑一樣的,可是vue構建的應用是一個但頁面應用如何讓他像正常的多頁面應用一樣,是在不停的改變路徑呢?