vue3组件

自定义单多选按钮

# 1. 单选封装

<template>
  <label class="custom-radio">
    <input
      type="radio"
      @input="handleClick"
      checked
      :name="groupName"
      :id="`radio-${groupName}`"
    />
    <div class="radio-btn" :style="{ '--size': size + 'px' }"></div>
    <span class="radio-text">{{ text }}</span>
  </label>
</template>
<script setup>
defineProps({
  groupName: {
    type: String,
    required: true
  },
  checked: {
    type: Boolean,
    default: false
  },
  size: {
    type: Number,
    default: 20
  },
  color: {
    type: String,
    default: '#000'
  },
  text: {
    type: String,
    default: ''
  },
  checkSize: {
    type: Number,
    default: 10
  },
  isDisabled: {
    type: Boolean,
    default: false
  }
})

const handleClick = e => {
  console.log('click', e.target.checked)
}
</script>

<style lang="scss" scoped>
.custom-radio {
  @include flex(flex-start);
  input {
    display: none;
  }
  /* 自定义单选按钮外观 */
  .radio-btn {
    display: inline-block;
    width: v-bind('size + "px"');
    height: var(--size);
    border: 1px solid v-bind('color');
    border-radius: 50%;
    position: relative;
    cursor: pointer;
  }
  .radio-text {
    margin-left: 10px;
  }
  input:checked + .radio-btn:after {
    content: '';
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: v-bind('checkSize + "px"');
    height: v-bind('checkSize + "px"');
    background-color: v-bind('color');
    border-radius: 50%;
  }
}
</style>

# 1.1. 使用方法:

<h-radio
  v-for="(item, i) in 3"
  :key="i"
  :groupName="'group1'"
  :index="i"
  :text="item"
  :checked="i == 1"
/>

# 2. 多选封装

<template>
  <label class="custom-checkbox">
    <input type="checkbox" :id="myCheckbox" checked />
    <span class="checkmark"></span>
  </label>
</template>
<script setup>
defineProps({
  checked: {
    type: Boolean,
    default: false
  },
  size: {
    type: Number,
    default: 15
  },
  color: {
    type: String,
    default: '#979797'
  }
})
</script>

<style lang="scss" scoped>
.custom-checkbox input {
  display: none;
}

/* 自定义复选框样式 */
.custom-checkbox .checkmark {
  display: inline-block;
  width: 15px;
  height: 15px;
  border: 1px solid #979797;
  position: relative;
  cursor: pointer;
}

/* 选中状态下的对勾样式 */
.custom-checkbox input:checked + .checkmark:after {
  content: ' ';
  position: absolute;
  left: 5px;
  top: 1px;
  width: 5px;
  height: 10px;
  border: solid #272636;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}
</style>

# 2.1. 使用

上次更新: