You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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
  });
}

说明

  1. 移除无效的import {store} from './store'语句
  2. 在插件的函数参数中添加store,Nuxt会自动将Vuex实例注入到上下文里
  3. 直接用store.commit调用定义好的mutation即可完成数据存储

之后你就可以在组件中通过this.$store.state.availableLanguages或者Vuex的辅助函数(如mapState)来访问这些语言数据了。


内容的提问来源于stack exchange,提问作者MrXQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:18:15