【发布时间】:2019-03-24 22:05:33
【问题描述】:
我正在调用商店中的操作以将数据发送到 API。 此调用由 @click 的 FormComponent 中的按钮触发:
<button type="button" @click="$store.dispatch('saveStoreDatas')">Click me</button>
如何提交按钮的父表单(省略代码)?我不能使用 ref,因为它在组件内部。
谢谢!
【问题讨论】:
我正在调用商店中的操作以将数据发送到 API。 此调用由 @click 的 FormComponent 中的按钮触发:
<button type="button" @click="$store.dispatch('saveStoreDatas')">Click me</button>
如何提交按钮的父表单(省略代码)?我不能使用 ref,因为它在组件内部。
谢谢!
【问题讨论】:
为点击处理程序添加一个单独的函数:
<button type="button" @click.prevent="submitToStore">Click me</button>
...
...
methods () {
submitToStore () {
// refs can be used here - get your form data and send it to the store
let formData = this.$refs.myForm.data()
this.$store.dispatch('saveStoreDatas', formData)
...
}
...
}
希望这会有所帮助。
【讨论】:
您需要发送一个动作并提交表单吗?通常,您可以将表单数据保存在存储中并在操作中发送。
如果确实需要提交表单,在子组件中发出事件,在父组件中监听事件。
子组件会这样。
<!-- child component template -->
<button type="button" @click="handleClick">Click me</button>
// child component script
methods: {
handleClick () {
this.$store.dispatch('saveStoreDatas')
this.$emit('clickSubmit')
}
}
这是它的父级。
<!-- parent template -->
<form ref="form">
<child-component @clickSubmit="submitForm">
</form>
// parent component script
methods: {
submitForm () {
this.$refs.form.submit()
}
}
【讨论】:
submitForm()有什么作用和神奇之处?
submitForm 在子组件的clickSubmit 事件上触发。 clickSubmit 在handleClick 方法中发出,将在单击button 时调用。 submitForm 获取父组件(this.$refs.form)中的表单元素并提交表单。
只需使用;
属性@click="$store.dispatch('saveStoreDatas');$emit('clickSubmit')"
<button type="button" @click="$store.dispatch('saveStoreDatas');$emit('clickSubmit')">Click me</button>
【讨论】: