这是父组件:
<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>
关于javascript - 无法使 vue.js element-ui 对话框在子组件内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49498786/