VueUse学习

⚡️ VueUse 学习


什么是VueUse

如果你了解reacthook,那么VueUse可以看做是vue版的hook库。如果不太了解,简单概括的话,VueUse是基于Composition API的常用函数集合。功能类似于lodash,免去用户自己去重复写一些常见的函数,如:防抖、节流、fetch等。

目前,VueUseStar数已经达到6.5k,npm周下载量达57800多次,且多次被尤大提及,完全可以放心食用。需要注意的是,虽然VueUse目前也支持Vue2,但Vue3下食用最佳。

为什么用VueUse

首先,VueUse相对于Vue全家桶中的其他库而言,使用优先级较低。其中包含的函数基本都能找到其他第三方库或者直接自己封装。但如果是以下两种情况,使用VueUse非常必要。

  • 资深Vue API CV工程师,当使用Composition API进行开发时,既想显得高端,又不想自己写工具类,那么VueUse十分符合需求。
  • 想学习Composition API分装工具函数库,可以学习VueUse源码,进行自己函数库的分装,获益良多。

如何使用

⏳Install

npm i @vueuse/core

⚠ From v6.0, VueUse requires vue >= v3.2 or @vue/composition-api >= v1.1

🌰简单栗子

<template>
  <div id="app">
    <h3>Mouse: {{x}} x {{y}}</h3>
    <h3>
      Counter: {{count}}
      <a @click='inc()' style='margin-right:10px'>+</a>
      <a @click='dec()'>-</a>
    </h3>
  </div>
</template>

<script setup lang="ts">
import { useMouse, useCounter } from '@vueuse/core'

const { x, y } = useMouse()
const { count, inc, dec } = useCounter()
</script>

🌐useFetch

1.简单使用

<template>
  <div>
    <transition>
      <p v-if="isFetching">
        loading: {{isFetching}}
      </p>
    </transition>
    <template v-if="!isFetching">
      <p>
        接口返回:data => {{data}}
      </p>
      <br />
      <p>
        接口返回:error => {{error}}
      </p>
    </template>
  </div>
</template>

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

const { isFetching, error, data } = useFetch('https://httpbin.org/get');
</script>

2.拦截器

import { useFetch } from '@vueuse/core';

const { isFetching, error, data } = useFetch('https://httpbin.org/get', {
  beforeFetch({ url, options, cancel }) {
    options.headers = {
      ...options.headers,
      Authorization: `hello world`,
    };

    return {
      options,
    };
  },
  afterFetch(ctx) {
    if (ctx.data.title === 'HxH') ctx.data.title = 'Hunter x Hunter';

    return ctx;
  },
  onFetchError(ctx) {
    if (ctx.data === null) ctx.data = { title: 'Hunter x Hunter' };

    ctx.error = new Error('Custom Error');

    return ctx;
  },
});

3.请求方式与相应格式

// get请求参数直接url拼接
const { isFetching, data, error } = useFetch('https://httpbin.org/get?id=1&name=111').get().text();

// post、put、delete在对应方法中传参
const { isFetching, data, error } = useFetch('https://httpbin.org/get')
   .post({ id: 1, name: 111 })
   .json();

// 也可以通过useFetch配置参数进行配置
const { isFetching, data, error } = useFetch(
  'https://httpbin.org/get',
  {
    method: 'POST',
    body: JSON.stringify({
      id: 1,
      name: 111,
    }),
  },
  { refetch: true }
).json()

4.自定义useFetch

项目中需要自定义useFetch,用于统一处理请求,包含:baseUrl、token、错误处理、统一返回数据等等

const useMyFetch = createFetch({
  baseUrl: 'https://my-api.com',
  options: {
    async beforeFetch({ options }) {
      const myToken = await getMyToken()
      options.headers.Authorization = `Bearer ${myToken}`

      return { options }
    },
  },
  fetchOptions: {
    mode: 'cors',
  },
})

const { isFetching, error, data } = useMyFetch('users')

VueUse常用方法总结

VueUse将所有方法按照功能性进行了分类,包含:Animation、Browser、Component、Formatters、Misc、Sensors、State、Utilities、Watch,详见vueuse.functions。其中较为常用的有:

  • useClipboard 复制到剪贴板
  • useFetch fetch请求
  • useFullscreen 全屏
  • useLocalStorage localStorage
  • useDebounceFn
  • useThrottleFn
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值