【问题标题】:How to access Vuex module actions from a component如何从组件访问 Vuex 模块操作
【发布时间】:2017-11-20 08:46:14
【问题描述】:

我定义了一个包含两个模块的商店,我正在尝试访问一个模块操作,我尝试这样做

this.$store.dispatch('load');

但我明白了:

[vuex] 未知动作类型:加载

我尝试了另一个选项,我在 google 中找到的东西,但没有任何效果,访问模块操作的正确方法是什么?

这是我的代码:

Vuex 定义:

let session = require('./store/session.js');
let options = require('./store/options.js');
const store = new Vuex.Store({
    modules: {
        session: session,
        options: options,
    },
});

options.js

 export default {
    state: {
        data: null,
    }, 
    mutations: {
        setOptions (state, payload) {
            console.log(payload);
        } 
    },
    actions: { 
        load( { commit }) {
            $.getJSON('options')
            .then(function (data) {
                commit('setOptions', data);
            });
        }
    },
    getters: {

    }

}

和我的应用组件:

export default {
    beforeCreate() {
         this.$store.dispatch('load');
    }
}

我的 vue 构建:

new Vue({
    el: "#app",
    router,
    store,
    render: h => h(App)
});

【问题讨论】:

  • 如果你在console.log(this.$store) 中加入beforeCreate() {} 钩子会发生什么?应该有一个 _actions 对象来显示所有可用的操作。
  • @visevo 该属性中没有属性,但是当我导入选项时它可以工作

标签: vuejs2 vuex


【解决方案1】:

我会考虑使用 vuex 的 mapActions 助手。这方面的文档可以在https://vuex.vuejs.org/guide/actions.html#dispatching-actions-in-components 找到。

本页示例如下:

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // map `this.increment()` to `this.$store.dispatch('increment')`

      // `mapActions` also supports payloads:
      'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')`
    })
  }
}

【讨论】:

    【解决方案2】:

    我解决问题 而不是做

     let options = require('./store/options.js');
    

    我做到了:

    import options from './store/options.js'
    

    现在可以了

    【讨论】:

    • 太棒了,我应该明白的。
    猜你喜欢
    • 2019-08-16
    • 2018-04-25
    • 2021-12-29
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2021-09-04
    • 2021-05-15
    • 2018-02-10
    相关资源
    最近更新 更多