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

How to trigger a form inside a component from VueX store

我正在商店中调用一个操作将数据发送到 API。 此调用是从 FormComponent 中的按钮触发的 @click :

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

只需使用;

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

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