代码之家  ›  专栏  ›  技术社区  ›  margherita pizza

VueJS将路由器传递到存储。js公司

  •  0
  • margherita pizza  · 技术社区  · 7 年前

    我有一个很好用的代码片段。 标题。vue

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

    百货商店js公司 (操作)

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

    它所做的是onLogout函数清除idToken并将用户重定向到欢迎屏幕。这很好用。 但同样 标题。vue componet我无法通过路由器在 百货商店js公司 。它表示路由器未定义。为什么会发生这种情况,我该如何解决? 这是我的密码。 标题。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)
        }
    

    百货商店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')
    
          }
    

    为什么这不起作用,有没有更有效的方法将路由器传递到商店。js,而不是每次都通过。

    2 回复  |  直到 7 年前
        1
  •  1
  •   DobleL    7 年前

    (对我来说)更好的方法是导入router对象,例如:

    路由器。js公司

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

    行动。js公司

    import router from '../my/path/to/router'
    
    //whithin an action
    router.push('/foo')
    
        2
  •  1
  •   Hammerbot    7 年前

    我认为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答案。一个问题已经存在相同的问题: How to navigate using vue router from Vuex actions

    这样,您就不必在每次想要重定向时都通过路由器。