Vue-Router 基础大全

101 阅读1分钟

1.如何重定向页面

  • 第一种方法
const router = new VueRouter({
    routes: [
        { path: '/a', redirect: '/b' }
    ]
})

  • 第二种方法
const router = new VueRouter({
    routes: [
        { path: '/a', redirect: { name: 'foo' }}
    ]
})
  • 第三种方法
const router = new VueRouter({
    routes: [
        { 
            path: '/a', 
            redirect: to =>{
                const { hash, params, query } = to
                if (query.to === 'foo') {
                    return { path: '/foo', query: null }
                }else{
                   return '/b' 
                }
            }
            
        }
    ]
})

2.如何获取路由传过来的参数?

  • 1.meta 路由元信息 写在routes配置文件中
{
    path: '/home',
    name: 'home',
    component: load('home'),
    meta: {
        title: '首页'
    },
},

获取方式 : this.$route.meta.title获取

  • query 传参
this.$route.push({
    path:'/home',
    query:{
        userId:123
    }
})

浏览器地址:http://localhost:8036/home?userId=123 

获取方式:this.$route.query.userId

  • params 要在路由地址上做配置
{
    path: '/home/:userId',
    name: 'home',
    component: load('home'),
    meta: {
        title: '首页'
    },
},

const userId = '123'
this.$router.push({ name: 'home', params: { userId } })

注意用params传参,只能用命名的路由(用name访问),如果用path,params 不起作用 this.$router.push({path:'/home',params:{userId}})不生效

3.路由之间怎样跳转?

    1. 声明式 通过内置组件 来跳转
    1. 编程式 通过router实例父push方法 router.push({path:'/home'})或者replace 方法 router.replace({path:'/home'})

4. route和router有什么区别

  route 是 '路由信息对象' 包括path, params,hash query,fullPath,matched,name等路由信息参数
  router是'路由实例对象',包括了路由跳转的方法,钩子函数等   

全局导航守卫有哪些? 如何使用

  • router.beforeEach: 全局前置守卫
  • router.berforeResolve : 全局解析守卫
  • router.afterEach: 全局后置钩子
import VueRouter from 'vue-router';
const router = new VueRouter({
    mode: 'history',
    base: '/',
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return { x: 0, y: 0 };
        }
    }
})
router.beforeEach((to, from, next) => {
    //...
    next();
})
router.beforeResolve((to, from, next) => {
    //...
    next();
})
router.afterEach((to, from) => {
    //...
});

5.导航守卫三个参数的意义

  • to :即将要去的路由对象

  • from : 当前导航要离开的路由对象

  • next : 函数必须调用

    next() : 进入下一个路由

    next(false) : 中断当前的导航

    next('/')或 next({path:'/'}) : 跳转到其他路由 ,当前导航被中断,及进入新的导航