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

<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 事件,以实现双向数据绑定。

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

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

<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,这样就可以实现双向数据绑定。

相关推荐

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

    2024-06-10 16:56:01       10 阅读
  2. 使用vue3+ts封装一个Slider滑块组件

    2024-06-10 16:56:01       5 阅读
  3. 如何二次封装一个Vue3组件库?

    2024-06-10 16:56:01       34 阅读
  4. 基于 Vue 3 封装一个 ECharts 图表组件

    2024-06-10 16:56:01       7 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-10 16:56:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-10 16:56:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-10 16:56:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-10 16:56:01       18 阅读

热门阅读

  1. 每个寒暑假学习一项新技能

    2024-06-10 16:56:01       11 阅读
  2. python小tips

    2024-06-10 16:56:01       8 阅读
  3. git命令

    git命令

    2024-06-10 16:56:01      8 阅读
  4. Python之Pandas详解

    2024-06-10 16:56:01       9 阅读
  5. 04-4.2.3 KMP 算法求 next 数组

    2024-06-10 16:56:01       13 阅读
  6. 【系统学C++】一、从C语言到C++(一)

    2024-06-10 16:56:01       11 阅读
  7. 关于MySQL 中的全局事务标识符GTID

    2024-06-10 16:56:01       9 阅读
  8. C# - 委托与事件

    2024-06-10 16:56:01       6 阅读
  9. 如何进行《我的世界》基于Spigot的插件开发

    2024-06-10 16:56:01       12 阅读