vue3相关use函数vueuse(一)「建议收藏」

vue3相关use函数vueuse(一)「建议收藏」更多文章 前言 这段时间开发,封装了非常多的use函数,大多是业务型函数,也有一些基础的功能函数,例如useTimeout等,最近在项目中使用了vueuse,发现其已经对绝大部分的基础功能都进行了封装

大家好,欢迎来到IT知识分享网。

更多文章

前言

这段时间开发,封装了非常多的use函数,大多是业务型函数,也有一些基础的功能函数,例如useTimeout等,最近在项目中使用了vueuse,发现其已经对绝大部分的基础功能都进行了封装(ahooks是针对react hooks进行的封装,react同学可以拿去参考),有些方法还是非常不错的可以直接使用,有些则是需要结合业务进行二次封装,这里简单介绍几个

useClipboard

useClipboard实现了复制功能

import { useClipboard } from '@vueuse/core'
const { text, copy } = useClipboard()
// 复制
const copyHandle = () => copy('123123123')
console.log(text) // 123123123

IT知识分享网

useCssVar

useCssVar可以用来动态设置css变量,如: var(--color),可以用来配合完成动态主题

IT知识分享网import { useCssVar } from '@vueuse/core'
// dom-ref
const el = ref(null)
const color = useCssVar('--color', el)

根据上述代码,可以做一下简单的二次封装,完成动态主题的效果,如下:

import { useCssVar } from '@vueuse/core'

export default el => {
  // 初始化颜色
  const color = useCssVar('--color', el)
  // 设置主题色,作为更新全局主题方法
  const setColor = color => color.value = color

  return {
    setColor,
    setFontColor
  }
}

useFetch

useFetch是对fetch请求的封装,返回了接口返回的数据(data)和loading状态(isFetching),还有初始化是否请求(immediate)、主动请求(execute)、以及终止请求方法(abort)、拦截器等等方法,是一个非常强大的api,且不需要在安装额外插件

IT知识分享网import { useFetch } from '@vueuse/core'
const { execute } = useFetch(url, { immediate: false })
execute()

useScriptTag

控制js脚本的加载时机(manual)、加载(load)、卸载(unload)、添加标签属性(deferasync)、脚本加载完毕做一些事情等等,配合资源可以做一些优化

import { useScriptTag } from '@vueuse/core'

const { scriptTag, load, unload } = useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  () => {
    console.log('loaded')
  },
  { manual: true, defer: true, async: true },
)

// 加载
await load()
// 卸载
await unload()

useTitle

设置浏览器标题

import { useTitle } from '@vueuse/core'
const title = useTitle('default title')
setTimeout(() => title.value = 'new title', 0)

onClickOutside

点击元素外部触发,通常写一些ui组件时会用到该方法,如:弹窗点击外部隐藏

// 目标元素
const target = ref(null)

onClickOutside(target, (event) => console.log('未点中目标元素'))

useDevicePixelRatio

获取设备像素比

import { useDevicePixelRatio } from '@vueuse/core'

const { pixelRatio } = useDevicePixelRatio()

useDraggable

元素拖拽,这个还是很好用的,但是有点小小的问题,初始化的时候只能定义lefttop的位置

<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; width: 200px; height: 200px; background: #f0f;">
    Drag me! 
  </div>
</template>

useMove

由于useDraggable不能初始化定义rightbottom的位置,所以结合useMousePresseduseMouse,封装了一个useMove,同样是拖拽功能,但是可以在leftrightbottomtop中选择其二定义初始化位置

封装如下:

import { useMousePressed, useMouse } from '@vueuse/core'
import { reactive, toRefs, watch } from '@vue/composition-api'

/** * 元素可拖拽时,计算元素位置,left和right取其一,top和bottom取其一 * @param right 元素初始化right位置 * @param left 元素初始化left位置 * @param top 元素初始化top位置 * @param bottom 元素初始化bottom位置 * @param target 元素ref */

export default ({
  right,
  left,
  top,
  bottom,
  target
}) => {
  // state
  const state = reactive({
    right,
    left,
    top,
    bottom
  })
  // useMousePressed
  const { pressed } = useMousePressed({ target })
  // useMouse
  const { x, y } = useMouse()
  // watch:监听鼠标移动计算left,top,right,bottom
  watch(
    [x, y],
    ([x1, y1], [x2, y2]) => {
      try {
        // 鼠标按下后移动开始计算位置
        if (pressed.value) {
          state.right = state.right - (x1 - x2)
          state.left = state.left + (x1 - x2)
          state.top = state.top + (y1 - y2)
          state.bottom = state.bottom - (y1 - y2)
        }
      } catch (error) {
        console.error(`error: ${error}`)
      }
    }
  )

  return {
    ...toRefs(state)
  }
}

使用:

import { templateRef } from '@vueuse/core'
import useMove from '@/hooks/useMove'

const target = templateRef(null)
// 位置
const { right, top } = useMove({ right: 30, top: 90, target })

useMousePressed

鼠标是否按下

import { templateRef, useMousePressed } from '@vueuse/core'

const target = templateRef(null) 
const { pressed } = useMousePressed({ target })

console.log(pressed) // 按下: true,起来: false

useMouse

鼠标位置

import { useMouse } from '@vueuse/core'

const { x, y } = useMouse()

结语

太多了先列举与部分,真是万物皆可封装啊

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/9354.html

(0)
上一篇 2023-02-12 17:00
下一篇 2023-02-12 19:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信