scenario

When vue + elementUi framework is used as background management system, el-Dialog can be encapsulated twice when pop-up box is needed to add/edit content, making the code simple and easy to maintain.

Child component adddialog.vue:

<template>
  <div>
    <el-dialog
      title="New"
      :visible.sync="show"
      @close="$emit('update:visible', false)"
    >
      <el-form>
        <el-form-item label="Name">
          <el-input v-model="name" />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
    export default {
        props: {
            visible: {
              type: Boolean.default: false}},data() {
            return {
              name: ' '.show: this.visible,
            };
          },
          watch: {
            visible(val) {
              this.show = val; }}}</script>
Copy the code

Used in the parent component:

<template>
    <div>
        <button @click="handleAdd">Open/close</button>
        <addDialog :visible.sync="addshow" />
    </div>
</template>
<script>
    import addDialog from "./addDialog.vue";
    export default {
        components: { addDialog },
        data() {
          return {
            addshow: false}; },methods: {
          handleAdd() {
            this.addshow = true; }}};</script>
Copy the code

Visible of props cannot be used to control show and hide directly in a subcomponent; an intermediate value show is required. Since el-Dialog closes with a visible value set, child components will report an error if they change the props value directly [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “visible”

$emit(‘update:visible’, false); $emit(‘update:visible’, false); Change the median value show to close.

Sync =”addshow” />

<addDialog
:visible="addshow"
@update:visible="newVal => addshow = newVal"
/>
Copy the code

When there is a requirement to add/modify the same pop-up box, the contents of the dialog need to be dynamically modified. You can pass additional parameters to the child component and listen in the child component Watch. The reason why watch is used is that sub-component rendering only performs one Created life cycle. If the change content must be written in Created, it needs to be used with V-IF, wrap the sub-component with V-IF, and reload the sub-component each time. At this time, the requirement of dynamic modification of dialog content can be met. However, the animation effect of the el-Dialog pop-up will disappear.