一、 用法
<template>
<div class="page-view">
<div>
isShow: {{ isShow }}
<button @click="isShow = !isShow">改变isShow</button>
inputValue: {{ inputValue }}
</div>
</div>
<!-- 在vue3中v-model是props和emit的结合 -->
<!-- 默认提供修饰符
v-model.trim(去掉两端空格)
v-model.number(只输入number)
v-model.lazy(change事件触发) -->
<ComponentModel v-model:inputValue.isModifiers="inputValue" v-model="isShow"></ComponentModel>
</template>
<script setup lang="ts">
import { ref, reactive, toRefs, onMounted} from 'vue'
import ComponentModel from '../components/ComponentModel.vue'
const isShow = ref<boolean>(true)
const inputValue = ref<string>('请输入表单数据')
</script>
<style scoped lang="less">
.page-view{
padding: 10px;
button{
width: 140px;
height: 40px;
border: 1px solid #ccc;
}
}
</style>
<template>
<div v-if="modelValue" class="component-model">
<h1>子组件</h1>
<div class="content">
<span>显示父组件数据modelValue: {{ modelValue }}</span>
<button @click="changeIsShow"> 改变父组件isShow</button>
<div>
内容:<input type="text" :value="inputValue" @input="changeInputValue">
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { emit } from 'process';
import { ref, reactive, toRefs, onMounted} from 'vue'
const props = defineProps<{
modelValue: boolean,
inputValue: string,
inputValueModifiers?: { //命名默认Modifiers 如有参数model + Modifiers
isModifiers: boolean //自定义修饰符
}
}>()
// defineProps({
// modelValue: Boolean,
// inputValue: String
// })
const emits = defineEmits(['update:modelValue', 'update:inputValue'])
const changeIsShow = () => {
emits('update:modelValue', false)
}
const changeInputValue = (e:Event) => {
const target = e.target as HTMLInputElement
emits('update:inputValue', props?.inputValueModifiers?.isModifiers ? target.value + '无自定义修饰符' : target.value)
}
</script>
<style scoped lang="less">
.component-model{
border: 2px solid #ccc;
margin: 10px;
padding: 10px;
font-size: 24px;
button{
width: 140px;
height: 40px;
border: 1px solid #ccc;
background-color: skyblue;
}
}
</style>
二、原理
通过el初始化赋值
addEventListener监听
结合emit和props更新
读取props->获取emits