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

Vue.js 2:如何将Vuex Store传递给Vue-Router组件

同时使用Vue Router和Vuex时,让组件获取Store的方法

嗨,这个问题其实很好解决!不管你有没有用Vue Router,只要把Vuex的Store正确注入到根Vue实例中,所有的路由组件(包括子组件)都能自动拿到Store实例,不用额外单独传递。具体步骤如下:

1. 在入口文件中同时注入Store和Router

通常你的项目入口是main.js,在这里你需要导入你的Store和Router配置,然后在创建根Vue实例时,把两者都传进去:

import Vue from 'vue'
import App from './App.vue'
// 导入你写的store.js里的store实例
import { store } from './store.js'
// 导入你的路由配置文件(比如router.js)
import router from './router.js'

new Vue({
  el: '#app',
  store, // 把store注入根实例
  router, // 把router也注入根实例
  render: h => h(App)
})

2. 在组件中访问Store

完成上面的步骤后,不管是普通组件还是路由组件,你都可以通过this.$store直接访问到Store的所有内容:

示例1:访问State中的数据

export default {
  computed: {
    // 获取store里的jwt状态
    currentJwt() {
      return this.$store.state.jwt;
    }
  }
}

示例2:调用Store的Action或Mutation

export default {
  methods: {
    async refreshToken() {
      // 调用store里的action
      await this.$store.dispatch('refreshJwt');
      // 调用store里的mutation
      this.$store.commit('UPDATE_JWT', newToken);
    }
  }
}

额外提示

如果你习惯用Vuex的辅助函数(比如mapState、mapActions),也可以直接在组件里使用,它们会自动识别this.$store:

import { mapState, mapActions } from 'vuex'

export default {
  computed: {
    ...mapState(['jwt'])
  },
  methods: {
    ...mapActions(['refreshJwt'])
  }
}

这样一来,所有组件都能轻松获取到Vuex的Store啦,完全不用因为Vue Router的存在而额外做特殊处理~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:41:06