vue3-子组件实现v-model/多v-model/自定义修饰符

84 阅读1分钟

自定义子组件实现v-model/多v-model/自定义修饰符

父组件

<template>
  <div>
    <div class="box">index组件</div>
    <div>show:{{ show }}</div>
    <div>text:{{ text }}</div>
    <t-button @click="show = !show">开关</t-button>
    <hr />
    <!--    带修饰符-->
    <c-vue v-model.con="show" v-model:textVal.con="text" />
    <!--    不带修饰符-->
    <!--    <c-vue v-model="show" v-model:textVal="text" />-->
  </div>
</template>

<script lang="ts">
export default {
  name: 'ApplyAWSIndex',
};
</script>
<script setup lang="ts">
import { ref } from 'vue';
import CVue from './C.vue';

const show = ref<boolean>(true);
const text = ref<string>('menffy');
</script>

<style scoped lang="less">
.box {
  background-color: yellow;
}
</style>

子组件

<template>
  <div style="border: 1px solid black; height: 500px; background-color: #3d87ff">
    我是C
    <div v-show="modelValue" style="border: 1px solid black; height: 100px; background-color: #9b066d">
      我是个显示区域
      <hr />
      <t-button @click="handleClick">开关</t-button>
      <hr />
      <input style="width: 500px" :value="textVal" @input="handleChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
interface propType {
  modelValue: boolean;
  // 默认的是modelModifiers这个名字
  modelModifiers?: {
    // 修饰符, 默认就是布尔值
    con: boolean;
  };

  textVal: string;
  // 自定义的v-model绑定值,其修饰符接收值格式:'变量+Modifiers'
  textValModifiers?: {
    // 修饰符, 默认就是布尔值
    con: boolean;
  };
}
const props = withDefaults(defineProps<propType>(), {
  modelValue: false,
  textVal: '',
});

interface emitType {
  (e: 'update:modelValue', showC: boolean): void;
  (e: 'update:textVal', textC: string): void;
}
const emit = defineEmits<emitType>();

const handleClick = () => {
  // 根据是否有修饰符,判断执行何种操作
  console.log(props?.modelModifiers?.con ? '默认modeValue.con修饰符生效了' : '默认modeValue的修饰符没生效');
  emit('update:modelValue', false);
};

const handleChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  // 根据是否有修饰符,判断执行何种操作
  emit('update:textVal', props?.textValModifiers?.con ? `${target.value}-textVal.con修饰符生效` : target.value);
};
</script>

<style scoped></style>