无法从Mounted()钩子Nuxt.js中的Vuex存储分派方法

时间:2018-09-11 10:28:52

标签: vue.js nuxt.js ssr

我在Mounted()引擎罩中从Vuex商店分派方法时遇到问题吗? 这是出现的错误。

enter image description here

我只是在挂接的钩子中进行此操作:this.$store.dispatch('setSeason', seasonValue);

我在官方文档中看到了如何初始化存储,但这不起作用...

这是我用于Vuex商店初始化的代码:

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

var d = new Date();
var n = d.getMonth();
var current_season = (n == 1 || n == 2 || n == 12) ? 1 : (n == 3 || n == 4 || n == 5) ? 2 : (n == 6 || n == 7 || n == 8) ? 3 : 4;

const store = () => {
    return new Vuex.Store({
        state: {
            locales: ['en', 'ru'],
            locale: 'ru',
            seasons: [{title: 'Зима', label: 'winter'}, {title: 'Весна', label: 'spring'}, {title: 'Лето', label: 'summer'}, {title: 'Осень', label: 'autumn'}],
            season: current_season,
            categories: {},
        },
        mutations: {
            SET_LANG(state, locale) {
                if (state.locales.indexOf(locale) !== -1) {
                  state.locale = locale
                }
            },
            SET_SEASON(state, season){
                if(season >0 && season <=4){
                    state.season = season
                }
            },
            SET_CATEGORY(state, menu){
                state.categories  = Object.assign({}, menu)
            }
        },

        actions: {
            async nuxtServerInit({commit}){
                let {data} = await axios.get("http://admin.duras.aws.kz/api/v1/categories", {
                  headers: {
                    'Content-Type': 'text/plain'
                  },
                  params: {
                    type: 'tree',
                    current_id: null
                  }
                })
                commit('SET_CATEGORY', data)
            },
            setSeason({commit}, value){
                commit('SET_SEASON', value);
            }
        }
    })

}
export default store;

2 个答案:

答案 0 :(得分:0)

在您的Vue实例上,您是否已添加Vuex存储?

它应该看起来像这样

import store from './store'

new Vue({
  ...
  store,
  ...  
})

答案 1 :(得分:0)

nuxt中有两种存储模式,一种是经典模式,例如您在store / index.js中手动创建商店

import Vuex from 'vuex'

const createStore = () => {
  return new Vuex.Store({
    state: {
      counter: 0
    },
    mutations: {
      increment (state) {
        state.counter++
      }
    }
  })
}

export default createStore

其他是模块。您只需在store(store / index.js,store / something.js等)文件夹中创建带有状态,操作和突变的文件,例如

export const state = () => ({
  counter: 0
})

export const mutations = {
  increment (state) {
    state.counter++
  }
}

https://nuxtjs.org/guide/vuex-store/

这两种方法都将允许您访问此文件。$ store已装入内部