天天看點

vue-router使用後在本地可以跳轉,test環境this.$router.push()失效問題

(錯誤方法)

一開始: 懷疑是this指向問題,試了下發現不是這個問題
      var that = this,
      that.$router.push()
然後懷疑是路由沒寫好:
      that.$router.push({name: '/home'})
      that.$router.push({path: '/home'})
      that.$router.push('/home')
      各種都試了下,沒用- -
 然後打斷點開始一一排查,又懷疑是mode: 'hash'/'history'導緻的,不是的,各種百度出來一堆亂七八糟的
      
           

正确的方法:

方法一: 加個redirect

我的問題主要在跳轉時,路由沒有加載完成,是以我拿不到$route.path,隻拿到/,這不是我想要的,說下解決 

import Vue from 'vue'
import Router from 'vue-router'
const Home = () => import('../pages/home') 

Vue.use(Router);

const router = new Router({
   routes: [
      { path: '/', 
        redirect: '/home', 
        hidden: true
       }, {
       path: '/home', 
       name: 'home', 
       component: Home
      }
   ]
})
           

方法二: watch監聽

watch: {  // 按需加載路由,監聽路由變化邏輯處理
  $route (to, from) {
     let _this = this   // this儲存下
     _this.$router.push({
        path: _this.$route.path,
        query: {
           id: _this.$cookies.get("id")
         }
    });
  }
},
           

H5傳回上個頁面: this.$router.back()

檢視更多解決方法

繼續閱讀