vue3 封装单选框组件

效果图:

一、封装思想:

在父组件定义数据 传入给子组件 并绑定 v-model  获取当前选中的值

vue3中的v-model

 <son v-model="msg"></son> 

等同于

<son :modelValue="msg" @updata:modelValue="val=>msg=val"></son>

 了解更多: vue2.0 和 vue3.0中的v-model

二、封装

子组件

<template>
  <div class="flexA list">
      <div
      v-for="(item, idx) in props.list"
      :key="item.label"
      :class="item.value === modelValue ? 'active' : ''"
      @click="emit('update:modelValue', item.value)"
      >
      <!-- @click="clickItem(item, idx)" -->
      {
   
   { item.label }}
    </div>
  </div>
</template>

<script setup lang="ts">

const props = defineProps<{
  list: : {
    label: string
    value: number | string
  }[];
  modelValue: string|number ;
}>();

const emit = defineEmits<{
  (event: "update:modelValue", value: number | string): void;
}>();

</script>

<style lang="scss" scoped>
.list {
  flex-wrap: wrap;
  div {
    margin: 6px 0;
    margin-right: 10px;
    padding: 8px 8px;
    font-size: 14px;
    background: #f6f7f9;
    border: 1px solid #f6f7f9;
  }
  .active {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
  }
}
</style>

 modelValue 可以接收到父组件 v-model 绑定的值

父组件

<template>
  <div class="content">
    <h3>1. 世界上最好的语言是?</h3>
    <cp-radio-btn :options="list1" v-model="firstAnswer"></cp-radio-btn>
    <h3>2.你最喜欢哪个奥特曼?</h3>
    <cp-radio-btn :options="list2" v-model="secondAnswer"></cp-radio-btn>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";

const firstAnswer = ref(0);
const list1 = [
  { label: "php", value: 1 },
  { label: "java", value: 2 },
  { label: "JavaScript", value: 3 },
  { label: "python", value: 4 },
];

const secondAnswer = ref(0);
const list2 = [
  { label: "迪迦", value: 1 },
  { label: "赛文", value: 2 },
  { label: "泰罗", value: 3 },
  { label: "雷欧", value: 4 },
];
</script>
<style lang="scss">
.content {
  padding: 20px;
  h3 {
    margin-bottom: 10px;
  }
}
</style>

父组件传递数据 并绑定v-model 拿到子组件选中的值

猜你喜欢

转载自blog.csdn.net/m0_46846526/article/details/128242622
今日推荐