Vue3中自定义组件上的v-model如何使用?

父组件:使用v-model双向绑定传值

子组件:

1.defineProps中接收的变量名固定为modelValue

(以下代码中,相当于把通过v-model传过来的gender用modelValue来替代,这是固定语法)

// 父组件
<script setup lang="ts">
import { ref } from 'vue'
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
const gender = ref(1) // 默认性别
</script>
<template>
  <CpRadioBtn :options="options" v-model="gender"></CpRadioBtn>
</template>
<style></style>

2.通过:emit('update:modelValue',value)直接修改值不用再向父组件传递事件

('update:modelValue'也是固定写法,value就是想要改成什么值,直接传参)

// 子组件
<script setup lang="ts">
defineProps<{
  options: { label: string; value: number }[]
  modelValue: number | string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: number | string): void
}>()
</script>

<template>
  <div class="cp-radio-btn">
    <a
      class="item"
      href="javascript:;"
      v-for="item in options"
      :key="item.label"
      :class="{ active: item.value == modelValue }"
      @click="emit('update:modelValue', item.value)"
      >{ { item.label }}
    </a>
    <!-- <a class="item" href="javascript:;">女</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>
 

猜你喜欢

转载自blog.csdn.net/weixin_48082900/article/details/129149267