使用vue3+ts封装一个Switch开关组件

js 复制代码
<template>
  <div class="switch" :class="{ 'switch-on': isOn }" @click="toggle">
    <div class="switch-button"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

// 定义组件的 props
interface Props {
  modelValue: boolean;
}

// 定义组件的 emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
}>();

// 使用 ref 创建一个响应式数据
const isOn = ref<boolean>(props.modelValue);

// 定义 toggle 方法来切换开关状态
const toggle = () => {
  isOn.value = !isOn.value;
  emit('update:modelValue', isOn.value);
};

// 从父组件接收 props
const props = defineProps<Props>();
</script>

<style scoped>
.switch {
  width: 50px;
  height: 25px;
  border-radius: 15px;
  background-color: #ccc;
  position: relative;
  cursor: pointer;
}

.switch-button {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #fff;
  position: absolute;
  top: 2.5px;
  left: 2.5px;
  transition: all 0.3s ease;
}

.switch-on {
  background-color: #4caf50;
}

.switch-on .switch-button {
  left: 27.5px;
}
</style>

在这个组件中,使用了 Vue 3 的 Composition API 和 TypeScript。定义了一个 isOn 响应式引用,它代表了开关的状态。toggle 方法用于切换 isOn 的值,并通过 emit 函数向父组件发送 update:modelValue 事件,以实现双向数据绑定。

组件的样式部分定义了开关的外观,包括开关本身和按钮的样式,以及开关打开和关闭时的不同状态。

要使用这个组件,可以在父组件中这样引入:

vue 复制代码
<template>
  <div>
    <switch v-model="switchValue" />
    <p>Switch is {{ switchValue ? 'On' : 'Off' }}</p>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import Switch from './Switch.vue'; // 假设 Switch 组件在这个路径下

const switchValue = ref(false);
</script>

在这个父组件中,使用了 v-model 来绑定 switchValueSwitch 组件的 modelValue prop,这样就可以实现双向数据绑定。

相关推荐
qq_12498707531 天前
基于node.js+vue的医院陪诊系统的设计与实现(源码+论文+部署+安装)
前端·vue.js·node.js·毕业设计
袁煦丞1 天前
9.12 Halo的“傻瓜建站魔法”:cpolar内网穿透实验室第637个成功挑战
前端·程序员·远程工作
科兴第一吴彦祖1 天前
在线会议系统是一个基于Vue3 + Spring Boot的现代化在线会议管理平台,集成了视频会议、实时聊天、AI智能助手等多项先进技术。
java·vue.js·人工智能·spring boot·推荐算法
universe_011 天前
day27|前端框架学习
前端·笔记
沙尘暴炒饭1 天前
前端vue使用canvas封装图片标注功能,鼠标画矩形框,标注文字 包含下载标注之后的图片
前端·vue.js·计算机外设
百思可瑞教育1 天前
Vue中使用keep-alive实现页面前进刷新、后退缓存的完整方案
前端·javascript·vue.js·缓存·uni-app·北京百思可瑞教育
yinuo1 天前
Uni-App跨端实战:APP的WebView与H5通信全流程解析(03)
前端
yinuo1 天前
Uni-App跨端实战:支付宝小程序WebView与H5通信全流程解析(02)
前端
木心操作1 天前
js生成excel表格进阶版
开发语言·javascript·ecmascript
GISer_Jing1 天前
sqb&ks二面(准备)
前端·javascript·面试