前言:
某次开发中,直接在vue生命周期中写了window对象的resize事件监听,我们经理推荐我去看看VueUse工具库;
官网:
什么是vueuse:
VueUse不是Vue.use,它是为Vue 2和3服务的一套Vue Composition API的常用工具集,是目前世界上Star最高的同类型库之一。它的初衷就是将一切原本并不支持响应式的JS API变得支持响应式,省去程序员自己写相关代码。
安装:
npm i @vueuse/core
使用:
eg:使用全屏对象
<template>
<div class="test" ref="testRef">全屏测试</div>
<div @click="enter">全屏</div>
</template>
<script setup lang="ts">
import { useFullscreen } from "@vueuse/core";
import { ref } from "vue";
const testRef = ref();
const { isFullscreen, toggle, enter, exit } = useFullscreen(testRef);
</script>
eg:使用日期格式化对象
<template>
{{ formatted }}
</template>
<script setup lang="ts">
import { useNow, useDateFormat } from "@vueuse/core";
const formatted = useDateFormat(useNow(), "YYYY-MM-DD HH:mm:ss");
</script>
eg:dom元素resize监听
<template>
<textarea ref="testRef" v-model="text"></textarea>
</template>
<script setup lang="ts">
import { useResizeObserver } from "@vueuse/core";
import { ref } from "vue";
const testRef = ref();
const text = ref<string>("");
useResizeObserver(testRef, ([entry]: any[]) => {
const { height, width } = entry.contentRect;
text.value = `${width};${height}`;
});
</script>
eg:浏览器复制
<template>
<textarea v-model="source"></textarea>
<button @click="copy()">
<!-- by default, `copied` will be reset in 1.5s -->
<span v-if="!copied">Copy</span>
<span v-else>Copied!</span>
</button>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useClipboard } from "@vueuse/core";
const source = ref("Hello");
const { text, copy, copied, isSupported } = useClipboard({ source });
</script>
看效果: