javascript - NuxtJS + Vuex — 存储中的数据

标签 javascript vuejs2 vuex nuxt.js

使用 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')
	}
}

但是我无法让它工作。文档说:

If you are using the Modules mode of the Vuex store, only the primary module (in store/index.js) will receive this action. You'll need to chain your module actions from there.

但是我不知道该怎么做。如何调用另一个模块/文件中定义的操作?

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

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

谢谢!

最佳答案

几周前我遇到了同样的问题,下面是我如何解决的:

========经典模式=========

store/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
    }
  })
}

store/modules/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
}



请注意 commit('base/SET_ERROR', err.response.data.message, { root: true }) 行,它调用另一个模块(称为 base)中的突变。以及 namespaced: true 选项,这是工作所必需的。

要了解有关 vuex 模块中命名空间的更多信息,请参阅文档:https://vuex.vuejs.org/en/modules.html


======== 模块模式 =========

新的“模块模式”使这更容易。您可以将所有文件放在一个文件夹中,并且不再需要“namespaced = true”。
以下是上述文件在模块模式下的样子:

store/index.js

export const state = () => ({})

export const actions = {
  async nuxtServerInit ({ commit }, { req }) {
    if (req.session.user && req.session.token) {
      commit('auth/SET_USER', req.session.user)
      commit('auth/SET_TOKEN', req.session.token)
    }
  }
}

store/auth.js

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

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

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 {
  state,
  getters,
  mutations,
  actions
}



要了解更多关于 nuxtjs 中的模块模式,请参阅文档:
https://nuxtjs.org/guide/vuex-store/#modules-mode

关于javascript - NuxtJS + Vuex — 存储中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478486/

相关文章:

javascript - (VueJS) Vuex getter 应该根据另一个模块状态变化进行更新

javascript - 从 promise 解析调用时 Vuex 存储未更新

vue.js - "TypeError: Cannot read property ' 得到 ' of undefined", Axios, Vue.JS

javascript - Vue.js + Vuex : How to mutate nested item state?

javascript - 我的开关无法识别我之前定义的变量

javascript - 为什么 jQuery spritely 动画在第二个 mouseenter 上播放额外的帧?

javascript - 在 JS 中迭代我的数组,但出现 "Cannot read property ' length' of undefined"错误

Javascript if 不返回 true

vuejs2 - Electron VueJS - 构建错误 - 无法注册应用程序协议(protocol)。在 app.asar 中找不到 ENOENT、\dist_electron\bundled

javascript - R 中的 "Icon"(ISOTYPE) 图表在 Javascript 中 Shiny