所以要是想通过封装组件支持v-model的使用,用v-model语法糖无疑是最好的选择
子组件定义使用modelValue进行接收父组件传递过来的值,定义事件update:modelValue通知父组件改变一些事情
举例使用:
封装子组件:cp-radio-btn
//子组件 cp-radio-btn
<script setup lang="ts">
// 通过v-model双向绑定实现计数器
const props = defineProps<{
modelValue: number
}>()
const emit = defineEmits<{
(e: 'update:modelValue', count: number): void
}>()
const btnClick = () => {
emit('update:modelValue', props.modelValue + 10)
}
</script>
<template>
<div class="cp-radio-btn">
计数器:{{ modelValue }} <br />
<button @click="btnClick">修改count</button>
//<button @click="$emit('update:modelValue', modelValue + 2)">修改count</button>
</div>
</template>
<style lang="scss" scoped></style>
父组件patient -使用子组件cp-radio-btn
使用 modelValue 像子组件传递数据,定义子组件通知的事件 @update:modelValue做事情
//父组件 patient
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const count = ref(0)
const updateCount = (num: number) => {
count.value = num
}
</script>
<cp-radio-btn :modelValue="count" @update:modelValue="updateCount"></cp-radio-btn>
//<cp-radio-btn :modelValue="count" @update:modelValue="count = $event"></cp-radio-btn>
如此就完成了数据的双向绑定;
在这,:modelValue="count" @update:modelValue="updateCount"就可以简写为v-model="count"
可以实现同上代码同样的效果
<cp-radio-btn v-model="count"></cp-radio-btn>
上面文章开始说了Vue3的v-model默认是解析成了:modelValue与@update:modelValue,下面说一下,如果你想修改这个默认的传值与事件的话,如何修改?
举个例子:这里换传值事件名字时(这里用OtherName举例)
使用v-model后面需要加上:OtherName
<cp-radio-btn v-model:OtherName="count"></cp-radio-btn>
子组件的传值以及事件都需要改为自定义的名称
<script setup lang="ts">
// 通过v-model双向绑定实现计数器
const props = defineProps<{
OtherName: number
}>()
const emit = defineEmits<{
(e: 'update:OtherName', OtherName: number): void
}>()
const btnClick = () => {
emit('update:OtherName', props.OtherName + 10)
}
</script>
<template>
<div class="cp-radio-btn">
计数器:{{ OtherName }} <br />
<button @click="btnClick">修改OtherName</button>
</div>
</template>
<style lang="scss" scoped></style>