【问题标题】:Pass data to a store?将数据传递到商店?
【发布时间】:2017-07-25 15:14:41
【问题描述】:

如何将数据从我的 vue 组件传递到商店?

这是我的组件:

methods: {
    ...mapActions('NavBar', [
        'fix',
    ]),
    onClick: function() {
        this.fix('my-data');
    },
    ....

在商店里:

actions: {           
   fix: ({ commit }) => {
    //get data here?
   },
},

【问题讨论】:

  • 它必须是一个动作(可以是异步的),还是一个突变(对存储的同步更改)也可以工作?
  • 两者都可以,虽然我也想知道操作以供将来参考。

标签: vue.js vuejs2 vuex


【解决方案1】:

VueJS 2.x 中的动作和突变可以采用一个附加参数(通常称为payload)和附加数据。

来自VueJS documentation on Mutations

您可以向 store.commit 传递一个附加参数,该参数称为 突变的有效载荷:

mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

在大多数情况下,有效负载应该是一个对象,以便它可以包含 多个字段,记录的变异也会更多 描述性:

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

对于Actions

Action 支持相同的有效负载格式和对象样式的调度:

// dispatch with a payload
store.dispatch('incrementAsync', {
  amount: 10
})

// dispatch with an object
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

关于如何定义动作的文档似乎不是很清楚,但看起来应该可以:

actions: {
  incrementAsync ({ commit, state }, payload) { ... }
}

【讨论】:

    猜你喜欢
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2016-02-23
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多