Vue 路由

概念

路由 : 路径和组件的映射关系
作用 : 实现单页面应用程序的页面切换

使用步骤

1. 下包
      yarn add vue-router
2. 导入
      import VueRouter from 'vue-router'
3. 安装插件
      Vue.use(VueRouter)
4. 创建路由规则数组
      const routes = [
       // 一个对象就是一个路由规则
       {}
      ]
5. 创建路由对象
       const router = new VueRouter({
            routes
       })
6. 将路由对象注入到 Vue 实例中
       new Vue({
            router
       })
7. 使用 router-view 组件占位
       <router-view />

声明式导航

是什么
    router-link 组件
作用
    1. 最终会渲染成 a 标签
    2. to 属性不用加 #, 自动判断是否要添加
    3. 当被点击时自动添加两个类名: router-link-active router-link-exact-active, 用于导航高亮
用法
    <router-link to="不用加#直接写路径"></router-link>
传参
    query 传参
	直接在 url 后面使用 ? 拼接参数即可
	$route.query.参数名
    params 传参
	1. 路由规则中配置 path : '/part/:name'
	2. 在路径上直接传参即可
	$route.params.参数名

路由配置

重定向

路由规则中添加属性: redirect, 值为路径
{ path: '/', redirect: '/find' }

404页面处理

路由匹配顺序是由上到下, 要写在路由规则数组的末尾
{ path: '*', component: NotFound }

路由模式

在创建路由对象时传入配置
new VueRouter({
  routes,
  mode: 'history'
})

编程式导航

跳转

$router.push('路径')
$router.push({
  path: '路径',
  name: 'name'
})

传参

$router.push({
  path: '路径',
  name: 'name',
  query: {},
  params: {}
})

接收参数的方法一样

注意事项:如果是用 path 跳转, 会自动忽略 params
	推荐使用 name + params 或 path + query 传参搭配

路由嵌套

1. 在配置规则中添加 children 属性
{ path: '/find', component: Find, children: [ {} ] }
2. 在父路由中使用 router-view 占位

导航守卫

全局前置守卫

作用 : 每次路由跳转之前会执行该守卫, 必须通过 next 决定是否放行
用法 :
      router.beforeEach((to, from, next) => {
        // 权限判断
      })
				

全局后置钩子

作用 : 分析、更改页面标题、声明页面等辅助功能
用法 : 
    router.afterEach((to, from, failure) => {
      // 业务代码
    })
Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐