VueUse学习笔记
VueUse 简介
VueUse 是一款基于Vue组合式API的函数工具集。官网地址(短时间不会出中文文档😭)
- 它基于Vue Composition Api (组合式API),只有在支持组合式API的环境下,才可以正常使用它。
- 它是一款函数工具集(可类比为lodash.js/ramda.js)
Element-Plus
中也使用了它
安装
- Installation
npm i @vueuse/core
- cdn
<script src="https://unpkg.com/@vueuse/shared"></script>
<script src="https://unpkg.com/@vueuse/core"></script>
将以 window.VueUse 的方式暴露到全局环境
使用
1.useVModel
v-model绑定的简写,props + emit -> ref
先创建一个组件:Test.vue
<template>
<div>
name:
<input v-model="_name"/>
age:
<input v-model="_age"/>
</div>
</template>
<script lang="ts" setup>
import { useVModel } from '@vueuse/core'
const props = defineProps({
name: String,
age: String,
})
const emit = defineEmits(['update:name', 'update:age'])
const _name = useVModel(props, 'name', emit)
const _age = useVModel(props, 'age', emit)
</script>
然后在index.vue中使用它
<template>
<div>
<Test
v-model:name="formData.name"
v-model:age="formData.age"
></Test>
{{ formData }}
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import Test from './Test.vue'
const formData = reactive({
name: 'lily',
age: '8',
})
</script>
2.useToggle
切换布尔值
<template>
<div>value:{{ value }}</div>
<button @click="toggle()">切换</button>
</template>
<script setup lang="ts">
import { useToggle } from '@vueuse/core'
const [value, toggle] = useToggle()
</script>
toggle
的第一个参数会覆盖返回的value,将不再是切换功能
toggle
的第一个参数为布尔值,不能传递其他类型
<!-- 会将 $event 传入,触发警告 -->
<button @click="toggleDark" />
<!-- 建议这样做 -->
<button @click="toggleDark()" />
3.useClipboard
复制功能
<template>
<div>剪贴板内容:{{text}}</div>
<input type="text" v-model="source">
<button @click="copy(source)">复制</button>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useClipboard } from '@vueuse/core'
const source = ref('Hello')
// text 粘贴的内容
// copy 粘贴函数
// copied 是否已复制
// isSupported 是否有复制权限
const { text, copy, copied, isSupported } = useClipboard({ source })
</script>
由于懒惰,不定时更新。😏未完待续...
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通