天天看点

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()

查看更多解决方法

继续阅读