[TOC]
实际开发中我们很少会直接使用原生的表单, 都是使用第三方的UI库, 其中的组件都支持”v-model”.
图片来源: Vue Ant UI

[
](https://2x.antdv.com/components/checkbox-cn)
接下来我们就讲下如何封装支持”v-model”的组件.
props和$emit
实际上要实现”v-model”并不复杂, 相关的api我们之前的课程学过, 只需要2部:
- 在”props”中定义个属性叫”modelValue”.
- 在组件内部通过”$emit(‘update:modelValue’, 值)”触发事件.
实现一个Dialog组件

实现父子组件, 父组件可以控制子组件显示隐藏, 子组件可以控制自身的隐藏.
// 子组件, 对话框
<template>
<article v-show="modelValue" class="a-dialog">
你好Vue3
<a @click="$emit('update:modelValue', false)">关闭</a>
</article>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
props: {
modelValue: {
type: Boolean,
},
},
});
</script>
<style>
// 样式在这里可以看到:
// https://github.com/any86/vue3-start/blob/master/src/components/Dialog.vue#L19
</style>
父组件中使用”v-model”:
<template>
<button @click="isShowDialog = !isShowDialog">显示/隐藏</button>
<br />
<Dialog v-model="isShowDialog"/>
<Dialog v-model:modelValue="isShowDialog"/>
</template>
<script lang="js">
import { defineComponent } from "vue";
import Dialog from './components/Dialog.vue';
export default defineComponent({
name: "App",
components:{Dialog},
data(){
return {isShowDialog:false}
},
});
</script>
v-model:isShow
上面的例子中”Dialog”组件在”props”上定义了”modelValue”, 这个名字看起来一点都不符合”显示隐藏”的语义, 所以我们想改一下名字, 只需要:
