vue.js - 将数据传递给商店?

标签 vue.js vuejs2 vuex

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

这是我的组件:

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

在商店里:

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

最佳答案

VueJS 2.x 中的 Actions 和 Mutations 可以使用一个额外的参数(通常称为 payload)和额外的数据。

来自VueJS documentation on Mutations :

You can pass an additional argument to store.commit, which is called the payload for the mutation:

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

In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive:

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

对于 Actions :

Actions support the same payload format and object-style dispatch:

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

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

文档似乎不太清楚如何定义操作,但看起来以下内容应该有效:

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

关于vue.js - 将数据传递给商店?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45307344/

相关文章:

vue.js - Vuex 在子组件中不起作用

vue.js - vue-material state change ui update 弄乱了布局

javascript - Vuex 突变更新状态,计算属性永远不会反射(reflect)标记中的更新

vue.js - 使用 axios 响应中的操作改变 vuex 存储状态 - 提交不起作用

javascript - 如何清除 vuejs 状态的Interval

vue.js - 如何通过 vue 组件中的 vuex 存储获取响应 ajax?

vue.js - 从父组件重置子组件的形式

javascript - 将 bootstrap.css 包含到 nuxt 项目的最佳方法是什么?

vue.js - Vue-router:beforeEnter guard 对于子路径不能正常工作

javascript - laravel vue 控制台中的缩进问题