无法使 vue.js element-ui 的对话框在子组件内工作

Cannot make vue.js element-ui's dialog work while it's inside a child component

这是父组件:

<template lang="pug">
  .wrapper
    el-button(type="primary", @click="dialogAddUser = true") New User
    hr
    // Dialog: Add User
    add-edit-user(:dialog-visible.sync="dialogAddUser")
</template>

<script>
import * as data from '@/components/partials/data'
import AddUser from './partials/AddUser'

export default {
  name: 'users',
  components: { AddUser },

  data () {
    return {
      users: data.users,
      dialogAddUser: false
    }
  }
}
</script>

这是子组件:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible.sync="dialogVisible", top="5vh")
    div 'el-dialog-body' - content goes here
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    }
  }
</script>

我可以打开 dialog,但是当使用 dialog 内右上角的按钮关闭对话框时,出现此错误:

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: "dialogVisible"

后来我试着玩,做了如下的操作,现在连dialog:

都打不开了
<template lang="pug">
  el-dialog(width="75%", title="New User", :visible.sync="visibleSync", top="5vh")
    div 'el-dialog-body' - content goes here 
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    },
    watch: {
      visibleSync (val) {
        this.$emit('update:dialogVisible', val)
      }
    },
    data () {
      return {
        visibleSync: this.dialogVisible
      }
    }
  }
</script>

如果 visible.sync 有效,则组件正在发出 update:visible 事件。

因此,不要在子项中发生变异,而是将事件传播给父项,而不是:

:visible.sync="dialogVisible"

:visible="dialogVisible", v-on:update:visible="visibleSync = $event"

完整代码:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible="dialogVisible", v-on:update:visible="visibleSync = $event", top="5vh")
    div 'el-dialog-body' - content goes here 
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    },
    watch: {
      visibleSync (val) {
        this.$emit('update:dialogVisible', val)
      }
    },
    data () {
      return {
        visibleSync: this.dialogVisible
      }
    }
  }
</script>

作为另一种选择,您可以直接从 v-on 侦听器发出,而无需 visibleSync 本地 属性:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible="dialogVisible", v-on:update:visible="$emit('update:dialogVisible', $event)", top="5vh")
    div 'el-dialog-body' - content goes here 
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    }
  }
</script>