应用v-model封装el-dialog组件实现双向绑定

始终以来都是通过子组件$emit("update:name",payload),父组件应用.sync事件后缀来实现双向绑定的,经揭示发现应用v-model封装自定义组件则更不便了解与应用,于是有了这次尝试与这篇文章

一个弹框作为一个组件,一个变量管制dialog显示和敞开,在dialog外部可敞开,父组件也可敞开

<template>  <div>    <!-- 父组件应用该组件,v-model的值能够是任意变量 -->    <dialog-a      v-model="show1"      other-prop="8888"    />    <el-button @click="handleOpenDialog">显示弹框</el-button>  </div></template><script>import DialogA from './dialog-a'export default {  components: {    DialogA  },  data() {    return {      show1: false    }  },  methods: {    handleOpenDialog() {      this.show1 = true    }  }}</script>
// 子组件<template>  <el-dialog    title="我是弹框A"    :visible="show"    width="80%"    @close="handleCloseElementDialog"  >    <!--    须要监听close事件    不能应用 v-on="$listeners"进行事件透传,    因为el-dialog的close事件无参数,会把show设置为undefined,    父组件的变量即会被设置为undefined    能够应用自定义事件进行一次包装    -->    <div>      <div>{{ otherProp }}</div>      <el-button @click="handleCloseElementDialog">敞开弹框</el-button>    </div>  </el-dialog></template><script>export default {  name: 'DialogA',  model: {    prop: 'show',    event: 'my-close'  },  props: {    show: {      type: Boolean,      default: false    },    // 其余props    otherProp: {      type: String,      default: 'otherProp'    }  },  methods: {    handleCloseElementDialog() {      this.$emit('my-close', false)    }  }}</script>