NuxtJS + Vuex - 商店中的数据

问题描述 投票:4回答:1

使用NuxtJS(VueJS框架),我试图从布局模板中的REST API获取一堆数据(不能使用经典的fech()或asyncData()方法)。

所以我正在使用vuexnuxtServerInit()动作。这样,无论当前页面如何,我都应该能够在加载应用程序期间直接收集所有数据。

但我无法让它发挥作用。

这是我的商店map.js文件:

import axios from 'axios'

const api = 'http://rest.api.localhost/spots'
 
export const state = () => ({
	markers: null
})

export const mutations = {
	init (state) {
		axios.get(api)
			.then((res) => {
				state.markers = res.data
			})
	}
}

export const actions = {
	init ({ commit }) {
		commit('init')
	}
}

而index.js(可以触发nuxtServerInit()):

export const state = () => {}

export const mutations = {}

export const actions = {
	nuxtServerInit ({ commit }) {
		// ??
		console.log('test')
	}
}

但我无法让它发挥作用。医生说:

如果您使用的是Vuex存储的模块模式,则只有主模块(在store / index.js中)才会收到此操作。您需要从那里链接模块操作。

但我不知道我将如何做到这一点。如何调用另一个模块/文件中定义的操作?

我试图复制各种例子,但从未让它们起作用;这是我能想到的最好的。

我错过了什么?如果需要,这里是repostore folder

谢谢!

javascript vuejs2 vuex nuxt.js
1个回答
5
投票

几个星期前,我遇到了同样的问题,这就是我解决它的方法: 存储/ index.js

import Vue from 'vue'
import Vuex from 'vuex'
import auth from './modules/auth'
import auth from './modules/base'

Vue.use(Vuex)

export default () => {
  return new Vuex.Store({
    actions: {
      nuxtServerInit ({ commit }, { req }) {
        if (req.session.user && req.session.token) {
          commit('auth/SET_USER', req.session.user)
          commit('auth/SET_TOKEN', req.session.token)
        }
      }
    },
    modules: {
      auth,
      base
    }
  })
}

存储/模块/ auth.js

const state = () => ({
  user: null,
  token: null
})

const getters = {
  getToken (state) {
    return state.token
  },
  getUser (state) {
    return state.user
  }
}

const mutations = {
  SET_USER (state, user) {
    state.user = user
  },
  SET_TOKEN (state, token) {
    state.token = token
  }
}

const actions = {
  async register ({ commit }, { name, slug, email, password }) {
    try {
      const { data } = await this.$axios.post('/users', { name, slug, email, password })
      commit('SET_USER', data)
    } catch (err) {
      commit('base/SET_ERROR', err.response.data.message, { root: true })
      throw err
    }
  },
  /* ... */
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}


Please notice the lines commit('base/SET_ERROR', err.response.data.message, { root: true }), which calls the mutation in another module (called base). And the namespaced: true option, which is required for this to work.

To learn more about namespacing in vuex modules, please refer to the documentation: https://vuex.vuejs.org/en/modules.html
© www.soinside.com 2019 - 2024. All rights reserved.