如何从 VueX 商店触发组件内的表单



我正在调用存储中的操作以将数据发送到 API。 此调用由 FormComponent 中的按钮触发,@click:

<button type="button" @click="$store.dispatch('saveStoreDatas')">Click me</button>

如何提交按钮的父形式(省略的代码(?我不能使用 ref,因为它在组件内。

谢谢!

是否需要调度操作提交表单?通常,您只需在商店中拥有表单数据并在操作中发送即可。

如果确实需要提交表单,请在子组件中发出一个事件,并在父组件中侦听该事件。

子组件将如下所示。

<!-- 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()
}
}

为点击处理程序添加一个单独的函数:

<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)
...
}
...
}

希望这有帮助。

只使用;

属性@click="$store.dispatch('saveStoreDatas');$emit('clickSubmit')"

<button type="button" @click="$store.dispatch('saveStoreDatas');$emit('clickSubmit')">Click me</button>

最新更新