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>

image

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>

image
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>

image

由于懒惰,不定时更新。😏未完待续...

posted @   icey-Tang  阅读(474)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示