【问题标题】:Pass on the form data from one component to another将表单数据从一个组件传递到另一个组件
【发布时间】:2019-12-16 12:39:32
【问题描述】:

我正在尝试通过按钮从表单中获取信息,该按钮不是表单所在组件的一部分。

目前的结构基本上是这样的:

->组件A(按钮在这里) --> 在组件 A 中,我导入了表单所在的另一个组件(B)

所以我正在尝试使用位于组件 A 中的按钮从组件 B 传递信息。

组件 B 不只是组件 A 的一部分(会使事情变得相对容易)的原因是因为它在其他几个地方使用。

在组件 A 中我有:

    `<ComponentB></ComponentB>
    <div class="padding">
        <button @onSubmit="onSubmit" class="add-button btn btn-md float- 
        right" 
        type="submit">Add items from component B</button>
    </div>`

这是我位于组件 A 中的导出默认值中的数据

从'./ComponentB'导入组件B; 从'vuex'导入{mapActions};

export default { name: "ComponentA", components:{ ComponentB }, data(){ return{ firstname: '', surname: '', dateOfBirth: '', isPolicyHolder: '', drivingLicence: licenceNumber: '', countryLicenced: '', coverEffectiveFrom: '', coverEffectiveTo: '', } }

我也有 vuex 状态,我试图将信息传递给单击按钮。

在组件 A 中,这是方法:

    `methods:{
    ...mapActions(['addDriver']),
    onSubmit(e){
        e.preventDefault();
        this.addDriver( this.firstname, 
                        this.surname, 
                        this.dateOfBirth,
                        this.isPolicyHolder,
                        this.licenceNumber,
                        this.countryLicenced,
                        this.coverEffectiveFrom,
                        this.coverEffectiveTo)
    }
}`

组件 B 只包含几个文本框和日期选择器。

总而言之,在单击按钮时,它应该将在组件 B 中输入的任何信息传递给组件 A 数据。

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    您必须创建一个 Vuex 状态来管理变量。然后,创建动作并变异以修改状态。之后,你就可以在组件 B 中得到你想要的了。

    const store = new Vuex.Store({
      state: {
        // your states
      },
      mutations: {
        // change state here sync
      },
      actions: {
        // call mutations here, but you can do this async as axios methods etc..
      },
      getters: {
        // need this only if state still needs some calculation.
      }
    }
    

    所以在你创造了这一切之后。您将能够调用上述操作

    this.$store.dispatch('ACTION')
    

    并获取组件B中的状态

    this.$store.state.stateYouWant
    

    或使用吸气剂

    this.$store.getters.getterYouCreated
    

    【讨论】:

    • 嗨,我确实创建了一个 vuex 状态管理器。不完全确定在哪里调用该操作? $store.dispatch('ACTION'),在组件 B 或 A 中?组件 B 包含所有文本框组件 A 包含要单击的按钮,以便将内容添加到组件 B 的状态中。
    • 所以你必须传递这个状态才能首先存储在组件A中。你必须调用组件A中的一个动作来存储状态。组件 B 你只需要状态。明白了吗?
    猜你喜欢
    • 2019-07-05
    • 1970-01-01
    • 2018-05-02
    • 2021-04-16
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多