封装一个自定义的单选按钮组件(vue3-ts)

 业务场景,需要类似如下图的一个单选按钮组件,所以自己封装一个可以随时复用

 

组件:cp-radio-btn

<script setup lang="ts">
defineProps<{
  sexList: { label: string; value: number | string }[]
  modelValue?: number | string
}>()
defineEmits<{
  (e: 'update:modelValue', value: number | string): void
}>()
</script>

<template>
  <div class="cp-radio-btn">
    <a
      class="item"
      href="javascript:;"
      v-for="item in sexList"
      :key="item.value"
      :class="{ active: modelValue == item.value }"
      @click="$emit('update:modelValue', item.value)"
      >{
   
   { item.label }}</a
    >
  </div>
</template>

<style lang="scss" scoped>
.cp-radio-btn {
  display: flex;
  flex-wrap: wrap;
  .item {
    height: 32px;
    min-width: 60px;
    line-height: 30px;
    padding: 0 14px;
    text-align: center;
    border: 1px solid var(--cp-bg);
    background-color: var(--cp-bg);
    margin-right: 10px;
    box-sizing: border-box;
    color: var(--cp-text2);
    margin-bottom: 10px;
    border-radius: 4px;
    transition: all 0.3s;
    &.active {
      border-color: var(--cp-primary);
      background-color: var(--cp-plain);
    }
  }
}
</style>

 使用:在使用这个组件时,传入对应的数组数据即可,如下:

const sexList = [
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 0
  }
]

<cp-radio-btn :sexList="sexList" v-model="PatientObj.gender"></cp-radio-btn>

仿vant组件,v-model这里绑定的数据为(number | string),根据业务需要,可以对绑定的数据类型进行修改。

猜你喜欢

转载自blog.csdn.net/luoxiaonuan_hi/article/details/130552049