vue switch 开关 可以自定义样式

效果如下
在这里插入图片描述在这里插入图片描述
下面是template html

<template>
	<div>
	    <label role="checkbox" :class="['switch', { value }]">
	      <input type="checkbox" class="switch-input" @change="toggle" />
	      <div class="switch-core" :style="{ backgroundColor: value ? '#11CED2' : '#E6EAF1' }">
	        <div
	          class="switch-button"
	          :style="{
	            transition: `transform 100ms`,
	            transform: value ? `translate3d(32px, 0px, 0px)` : null
	          }"
	        ></div>
	      </div>
	      <span class="switch-label label-right" v-if="value">ON</span>
	      <span class="switch-label label-left" v-else>OFF</span>
	    </label>
	    </div>
</template>

下面是script 逻辑

<script>
export default {
  data () {
    return {
      value: true,
    }
  },
  methods: {
    toggle(event) {
      this.value = !this.value;
      console.log(this.value)
    }
  },
}
</script>

下面的是 style样式

<style>
.switch {
  display: inline-block;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  user-select: none;
  font-size: 10px;
  cursor: pointer;
}
.switch-input {
  display: none;
}

.switch-label {
  position: absolute;
  top: 0;
  font-weight: 600;
  color: white;
  z-index: 2;
}

.switch-label.label-left {
  left: 20px;
  line-height: 20px;
  border-top-left-radius: 2px;
  border-bottom-left-radius: 2px;
  color: #b5bdc8;
}

.switch-label.label-right {
  right: 20px;
  line-height: 20px;
  border-top-right-radius: 2px;
  border-bottom-right-radius: 2px;
}
.switch-core {
  width: 50px;
  height: 20px;
  border-radius:10px;
  line-height: 20px;
  display: block;
  position: relative;
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  transition: border-color 0.3s, background-color 0.3s;
  user-select: none;
}
.switch-button {
  width: 16px;
  height: 16px;
  display: block;
  position: absolute;
  overflow: hidden;
  top: 2;
  left: 2;
  z-index: 3;
  transform: translate3d(0, 0, 0);
  background-color: rgba(255, 255, 255, 1);
  border-radius: 10px;
  margin-top: 2px;
  margin-left: 2px;
}
</style>

你可能感兴趣的:(vue switch 开关 可以自定义样式)