从 Vue 中的插槽更新父级中的状态
Update state in parent from slot in Vue
我是 Vue 的新手,目前遇到了一个问题。我在我的项目中使用 Vuetify,我有一个 v-dialog 组件,带有这样的插槽:
<template>
<v-row>
<v-dialog v-model="dialog" max-width="600px">
<template v-slot:activator="{ on }">
<v-btn class="ma-3" color="info" v-on="on">{{ text }}</v-btn>
</template>
<slot></slot>
</v-dialog>
</v-row>
</template>
在这个组件中,我将传递一个表单作为插槽,并且我希望能够在提交表单时关闭模式。来自 React 背景,当我在插槽中提交表单时,我会简单地传递一个将对话框变量设置为 false 的函数。我无法弄清楚如何在 Vue 中最好地完成这项工作。我在 google 时找到的示例对于如此简单的操作来说似乎过于复杂。
谢谢
如果您希望 parent 关闭对话框,那么您应该(可能)也让 parent 负责打开对话框。否则,您最终可能会遇到组件相互争夺控制权的情况。
这很容易做到。让 parent 将 属性 传递给启用或禁用对话框的自定义组件。由于 parent 也将表单作为插槽提供,因此 parent 可以处理来自该表单的事件并正确设置 属性。
如果您详细了解插槽范围 here,
That slot has access to the same instance properties (i.e. the same “scope”) as the rest of the template.
因为您是通过 slot
传递 form
,所以您已经可以访问 parent
组件实例。
此外,如文档中所述,记住它很好
Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.
因此,当您编写组件时,
<template>
<ModalComponent>
<form @submit="toggleModalVisibility">
...
</form>
</ModalComponent>
</template>
传递给 form
的任何方法都可以访问父组件的 state
。
现在,如果您可以设置一个数据 属性 来切换父项中模态组件的可见性,并设置一个方法来切换此 属性
data: () => {
return {
showModal: false //or true
}
},
methods: {
toggleModalVisibility() {
this.showModal = !this.showModal;
}
}
您可以将此方法分配给表单的 onSubmit 处理程序
form @submit="toggleModalVisibility"
我是 Vue 的新手,目前遇到了一个问题。我在我的项目中使用 Vuetify,我有一个 v-dialog 组件,带有这样的插槽:
<template>
<v-row>
<v-dialog v-model="dialog" max-width="600px">
<template v-slot:activator="{ on }">
<v-btn class="ma-3" color="info" v-on="on">{{ text }}</v-btn>
</template>
<slot></slot>
</v-dialog>
</v-row>
</template>
在这个组件中,我将传递一个表单作为插槽,并且我希望能够在提交表单时关闭模式。来自 React 背景,当我在插槽中提交表单时,我会简单地传递一个将对话框变量设置为 false 的函数。我无法弄清楚如何在 Vue 中最好地完成这项工作。我在 google 时找到的示例对于如此简单的操作来说似乎过于复杂。
谢谢
如果您希望 parent 关闭对话框,那么您应该(可能)也让 parent 负责打开对话框。否则,您最终可能会遇到组件相互争夺控制权的情况。
这很容易做到。让 parent 将 属性 传递给启用或禁用对话框的自定义组件。由于 parent 也将表单作为插槽提供,因此 parent 可以处理来自该表单的事件并正确设置 属性。
如果您详细了解插槽范围 here,
That slot has access to the same instance properties (i.e. the same “scope”) as the rest of the template.
因为您是通过 slot
传递 form
,所以您已经可以访问 parent
组件实例。
此外,如文档中所述,记住它很好
Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.
因此,当您编写组件时,
<template>
<ModalComponent>
<form @submit="toggleModalVisibility">
...
</form>
</ModalComponent>
</template>
传递给 form
的任何方法都可以访问父组件的 state
。
现在,如果您可以设置一个数据 属性 来切换父项中模态组件的可见性,并设置一个方法来切换此 属性
data: () => {
return {
showModal: false //or true
}
},
methods: {
toggleModalVisibility() {
this.showModal = !this.showModal;
}
}
您可以将此方法分配给表单的 onSubmit 处理程序
form @submit="toggleModalVisibility"