【问题标题】:How to trigger a form inside a component from VueX store如何从 VueX 商店触发组件内的表单
【发布时间】:2019-03-24 22:05:33
【问题描述】:

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

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

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

谢谢!

【问题讨论】:

    标签: forms vue.js store vuex


    【解决方案1】:

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

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

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您需要发送一个动作提交表单吗?通常,您可以将表单数据保存在存储中并在操作中发送。

      如果确实需要提交表单,在子组件中发出事件,在父组件中监听事件。

      子组件会这样。

      <!-- 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 事件上触发。 clickSubmithandleClick 方法中发出,将在单击button 时调用。 submitForm 获取父组件(this.$refs.form)中的表单元素并提交表单。
      【解决方案3】:

      只需使用;

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

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

      【讨论】:

        猜你喜欢
        • 2017-05-03
        • 2017-06-30
        • 2018-07-17
        • 2021-05-25
        • 1970-01-01
        • 1970-01-01
        • 2019-01-13
        • 2020-06-18
        • 2018-12-21
        相关资源
        最近更新 更多