记录一下开发中用到的v-model修饰符
页面呈现
父组件
<div>
<h1>vue3 v-model自定义修饰符</h1> <br>
<div>
父组件中显示的数据: {{title}}
</div>
<br>
<ModifiersVue type="customize" v-model:title.toupper="title"/>
<br>
<!-- v-model简写方式 -->
<ModifiersVue type="default" v-model.slice="title"/>
</div>
<script lang="ts" setup>
import ModifiersVue from './components/Modifiers.vue';
import { ref } from 'vue'
const title = ref('This is the parent component message')
</script>
子组件
<template>
<div>
<button v-if="type === 'customize'" @click="changTitle">修改标题为大写</button>
<button v-if="type === 'default'" @click="changTitle">截取标题长度</button>
</div>
</template>
<script lang="ts" setup>
interface Props {
type: string,
title?: string,
titleModifiers?: { toupper: boolean },
// 如果父组件简写成v-model 则props能收到以下参数
modelValue?: string,
modelModifiers?: { slice: boolean }
}
const props = defineProps<Props>()
const emit = defineEmits(['update:title', 'update:modelValue'])
const changTitle = () => {
if(props.titleModifiers?.toupper) {
emit('update:title' , props?.title?.toUpperCase())
}
if(props.modelModifiers?.slice) {
emit('update:modelValue', props.modelValue?.slice(0, 3))
}
}
</script>
也可以写多个v-model 用法和写一个类似,就不做详细代码贴图