vue3 实现自定义radio

  • 需求背景
  • 解决效果
  • bgRadio.vue

需求背景

实现一个自定义选中样式的 radio
在这里插入图片描述

解决效果

在这里插入图片描述

bgRadio.vue

<!--/**
* @author: liuk
* @date: 2024/01/25
* @describe: 背景单选框
* @email: [email protected]
*/-->
<template>
  <div class="radio-wrap">
    <label class="radio-label" :for="modelValue" @click.prevent="radioValue = !radioValue">
      <input type="radio" :id="modelValue"  :checked="radioValue" />
      <i></i>
    </label>
  </div>
</template>

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

const props=  defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

const radioValue = computed({
  get() {
    console.log(props.modelValue,333)
    return props.modelValue;
  },
  set(val) {
    emit('update:modelValue', val);
  },
})
</script>

<style lang="scss" scoped>
.radio-wrap {
  display: inline-block;

  .radio-label {
    position: relative;
    top: 5px;
    display: inline-block;
    height: 25px;
    padding-left: 25px;
    cursor: pointer;
    font-size: 13px;
    margin-right: 5px;
    font-weight: normal;

    &.select {
      color: #dfae64;
    }

    input {
      position: absolute;
      left: -1px;
      top: 6px;
      z-index: -1;
      /*给与input标签相邻的i标签设置伪元素*/
      & + i::after {
        position: absolute;
        content: '';
        top: 5px;
        left: 8px;
        width: 13px;
        height: 13px;
      }

      & + i::before {
        position: absolute;
        content: '';
        top: 5px;
        left: 8px;
        width: 13px;
        height: 13px;
        border: 1px solid #0a0a0a;
        box-sizing: border-box;
        background: #fff;
      }

      /*input radio被选中后,给它相邻的i::after 设置样式*/
      &:checked + i::after {
        //background: url('@/assets/images/login/check.png') no-repeat center/cover;
        background: #0a0a0a;
      }
    }
  }
}
</style>

你可能感兴趣的:(#,vue实践,vue.js,javascript,ecmascript)