【问题标题】:Vuex unable to use modulesVuex 无法使用模块
【发布时间】:2020-02-13 06:01:36
【问题描述】:

我将 Vue 与 Webpacker 与 Rails 一起使用。我在使用 Vuex 时遇到了一些问题,特别是在使用模块方面。

application.js:

import store from '../store/store'
Vue.prototype.$store = store;


document.addEventListener('turbolinks:load', () => {
  axios.defaults.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
  const app = new Vue({
    el: '[data-behavior="vue"]',
    store
  })
})

store.js:

import Vue from 'vue/dist/vue.esm'
import Vuex from 'vuex';
import axios from 'axios';
import itemstore from'./modules/itemstore'
Vue.use(Vuex)

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

const store = new Vuex.Store({
............
  modules: {
    itemstore
  }

})


export default store;

itemstore.js:

import axios from 'axios';


const itemstore = {
  state: {
    items: [],
},
actions: {
    loadItems ({ commit }) {
        axios
        .get('/items.json')
        .then(r => r.data)
        .then(items => {
            commit('SET_ITEMS', items);
        })
    }
},
mutations: {
    SET_ITEMS (state, items) {
        state.items = items
    }
},
}

export default itemstore;

在我的组件中:

    mounted () {
      this.$store.dispatch('loadItems')
    },
    computed: {
        ...mapState([
            'items'
        ]),
      }

首先要导入主商店我需要Vue.prototype.$store = store;

第二次,一旦我将这些状态、动作和突变从 store.js 移动到 itemstore.js,项目就会变得未定义。我做错了什么?

【问题讨论】:

  • itemstore 需要以某种方式作为模块输入。我不在我的模块中使用这种语法。这取决于您使用的是哪些库,但您应该查看有关声明模块 itemstore 的文档。
  • 你不应该需要Vue.prototype.$store = store,它应该是自动的。您似乎没有包含无法正常工作的示例,因此很难推测问题可能是什么。您访问模块的方式取决于您是否使用命名空间。
  • @TheMikeInNYC 我也尝试使用 const state、const actions 等创建模块,但结果是一样的。
  • @skirtle 我用一个例子更新了答案,但基本上我把东西从 store.js 移到了模块中,它不再在组件中可用。
  • 1.您能否提供一个组件代码示例,包括您看到的错误消息? 2. 你能确认你没有使用命名空间吗? vuex.vuejs.org/guide/modules.html#namespacing 3. 你导入 Vue 的方式引起了我的注意。通常它只是import Vue from 'vue',最后没有/dist/vue.esm 位。确保在所有文件中导入 Vue 的方式保持一致,否则最终可能会得到库的多个副本,每个副本都有部分配置。

标签: vue.js vuex


【解决方案1】:

namespaced 设置将导致商店的actionsmutationssetters 基于模块名称进行命名空间。然而,模块的state 总是在state 中被分离到它自己的子树中,即使没有使用命名空间。

所以这行不通:

...mapState([
   'items'
]),

这是在根状态下寻找items 属性。

你可以使用类似的东西:

...mapState({
    items: state => state.itemstore.items
})

你可能会尝试这样写:

...mapState('itemstore', ['items'])

但是,将模块名称作为第一个参数传递给 mapState 仅适用于 namespaced 模块。

【讨论】:

  • 我通过使用您建议的第二个选项并将 namespaced: true 添加到 store 模块使其正常工作。最后我更改了 this.$store.dispatch('itemstore/loadItems')。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-12-22
  • 2017-01-28
  • 2017-10-01
  • 1970-01-01
  • 2020-07-24
  • 2021-01-27
  • 2021-02-26
  • 2020-10-01
相关资源
最近更新 更多