美文网首页
vue3自定义switch组件[上篇]

vue3自定义switch组件[上篇]

作者: 硅谷干货 | 来源:发表于2022-03-08 11:02 被阅读0次

前言

项目中需要用到switch这个开关组件,但是又不想用太重量级的组件库了,加载量太大,没必要,所以自己定制了一个,借鉴了一下we-ui的样式。很简单的几行代码,大家可以自己修改样式。

实现效果

image.png

创建SwitchButton.vue 组件

<template>
  <span class="switch" :class="{ 'switch-on': isOn }" @click="toggle"></span>
</template>

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

const props = defineProps({
  modelValue: {
    type: [Number, String, Boolean],
  },
  checked: {
    type: [Number, String, Boolean],
  }
});

const emits = defineEmits(["change", "update:checked"]);

const isOn = computed(() => {
  return props.checked;
});

const toggle = () => {
  emits("update:checked", !isOn.value);
  emits("change", !isOn.value);
};
</script>

<style lang="scss" scoped>
.switch {
  display: block;
  position: relative;
  width: 42px;
  height: 22px;
  border: 1px solid #dfdfdf;
  outline: 0;
  border-radius: 11px;
  box-sizing: border-box;
  background-color: #dfdfdf;
  transition: background-color 0.1s, border 0.1s;
  cursor: pointer;
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 40px;
    height: 20px;
    border-radius: 10px;
    background-color: #fdfdfd;
    transition: transform 0.35s cubic-bezier(0.45, 1, 0.4, 1);
  }
  &::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 20px;
    height: 20px;
    border-radius: 10px;
    background-color: #ffffff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
    transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35);
  }
}

.switch-on {
  border-color: #0a59f7;
  background-color: #0a59f7;
  &::before {
    border-color: #0a59f7;
    background-color: #0a59f7;
  }
  &::after {
    transform: translateX(20px);
  }
}
</style>

使用

<!-- 接收消息通知 -->
<div class="item-box cursor-pointer">
  <span> 接收消息通知 </span>
  <switch-button v-model:isOn="isOn" @change="onChange"></switch-button>
</div>

下篇: vue3自定义switch组件[下篇] - 简书 (jianshu.com)

点赞加关注,永远不迷路

相关文章

网友评论

      本文标题:vue3自定义switch组件[上篇]

      本文链接:https://www.haomeiwen.com/subject/jrharrtx.html