Nuxt.js中如何从axios.js访问Vuex Store存储语言数组
在Nuxt中如何将Axios拦截器获取的语言数组存入Vuex Store?
我有一个axios.js插件文件,通过拦截器从每次API响应中提取可用语言并存入comingLangs[]数组。现在想把这个数组存入Vuex Store,但直接用import {store} from './store'会报错Cannot find module './store',求解决方法。
现有代码
plugins/axios.js
import {store} from './store' // 无效,报错 export default function ({$axios, i18n}, inject) { let comingLangs=[] const apiClient = $axios.create({ headers: { 'X-localization': i18n.locale, } }); inject('apiClient', apiClient); apiClient.interceptors.response.use(function (response) { // 检查响应是否包含meta_tags if (response.data.content.meta_tags !== undefined && response.data.content.meta_tags) { // 将响应中的语言提取到数组 comingLangs = Object.keys(response.data.content.meta_tags.alternative) store.commit("SET_AVAILABLE_LANGUAGES",comingLangs) // 想要存入store的位置 } return response }); }
store/index.js
export const state = () => ({ availableLanguages: [], }) export const mutations = { SET_AVAILABLE_LANGUAGES(state, payload) { state.availableLanguages = payload }, }
解决方案
Nuxt的插件函数会自动注入上下文对象,其中包含Vuex的store实例,不需要手动import。直接修改插件的参数解构即可:
修改后的plugins/axios.js代码:
export default function ({$axios, i18n, store}, inject) { let comingLangs = [] const apiClient = $axios.create({ headers: { 'X-localization': i18n.locale, } }); inject('apiClient', apiClient); apiClient.interceptors.response.use(function (response) { // 检查响应是否包含meta_tags if (response.data.content.meta_tags !== undefined && response.data.content.meta_tags) { // 将响应中的语言提取到数组 comingLangs = Object.keys(response.data.content.meta_tags.alternative) store.commit("SET_AVAILABLE_LANGUAGES", comingLangs) // 直接使用注入的store提交mutation } return response }); }
说明
- 移除无效的
import {store} from './store'语句 - 在插件的函数参数中添加
store,Nuxt会自动将Vuex实例注入到上下文里 - 直接用
store.commit调用定义好的mutation即可完成数据存储
之后你就可以在组件中通过this.$store.state.availableLanguages或者Vuex的辅助函数(如mapState)来访问这些语言数据了。
内容的提问来源于stack exchange,提问作者MrXQ
相关产品推荐
相关产品推荐

