【问题标题】:VueJS passing router to the store.jsVueJS 将路由器传递给 store.js
【发布时间】:2026-01-14 20:55:02
【问题描述】:

我有一个运行良好的代码代码 sn-p。 header.vue

onLogout(){
      this.logout({ router: this.$router });
    }

store.js(操作)

logout({commit}, {router}){
  commit('clearAuthData')
  router.replace('/')
}

它的作用是 onLogout 函数清除 idToken 并将用户重定向到欢迎屏幕。这工作正常。 但是在同一个 header.vue 组件中,我无法通过路由器并在 store.js 中读取它。它说路由器未定义。为什么会发生这种情况,我该如何解决? 这是我的代码。 header.vue

onLogin () {

        const formData = {
          email: this.email,
          password: this.password,
          returnSecureToken:true
        }
        this.$store.dispatch('login',{
         email: formData.email,
         password: formData.password
       },{ router: this.$router })
      console.log(formData)
    }

store.js(操作)

login({commit},{router},authData){
      axios.post('http://localhost/laravel_back/public/api/login',authData

      )
        .then(res => {
          console.log("Backend response",res)
          commit('authUser',{
            token:res.data[0].token,
            userName:res.data[1][0].fname,
            id:res.data[2][0].id,
            type:res.data.type
        })})
        .catch(error => console.log(error))
        router.replace('/student')

      }

为什么这不起作用,除了每次都传递之外,还有更有效的方法将路由器传递给 store.js。

【问题讨论】:

标签: vue.js vuejs2 vue-router


【解决方案1】:

更好的方法(对我来说)它只是导入路由器对象,例如:

router.js

const router = new Router({
  mode: 'history',
  routes
})

export default router

actions.js

import router from '../my/path/to/router'

//whithin an action
router.push('/foo')

【讨论】:

  • 我的路由器对象在 main.js 中。我的 routues.js 有这样的东西“export const routes = [ {path:'/findYourAccount',component:findYourAccount}, {path:'/',component:welcom...]
  • 所以从 main 导入它,这没有问题,我喜欢将最终对象 (VueRouter) 或 (Vuex.Store) 导出到它们各自的文件中,并且只在 main 中组装模块跨度>
【解决方案2】:

我认为一个 VueX 动作只能接受一个参数。所以你必须在这些参数中包含路由器:

this.$store.dispatch('login',{
    email: formData.email,
    password: formData.password,
    router: this.$router
})

login({commit}, options){
    return axios.post('http://localhost/laravel_back/public/api/login',{email: options.email, password: options.password}).then(res => {
        console.log("Backend response",res)
        commit('authUser', {
            token:res.data[0].token,
            userName:res.data[1][0].fname,
            id:res.data[2][0].id,
            type:res.data.type
        })
        options.router.replace('/student')
    }).catch(error => console.log(error))
}

但最好使用@DobleL 答案。 A question已经有同样的问题:How to navigate using vue router from Vuex actions

有了这个,你就不必每次要进行重定向时都通过路由器。

【讨论】:

  • 什么是 vuex-router-sync 我以前也见过。但我无法理解这个概念。
  • 我的错,阅读文档后,它并不适合您的用例。如*.com/questions/40736799/… 所述,您应该直接在商店中导入路由器