vue路由使用

基础

  • 概念
- router是路由器
- routes是一组路由
- route某个路由(route.query、route.params、route.hash--#后面的,包含#)
const router = new VueRouter({
  routes
})
new Vue({
  router,
})
  • 模式
- hash模式
以参数形式传给单页面文件,只需要保证index.html这个文件路径真实就可以了
- history模式
这种模式需要后端支持,因为如http://xxx/自定义路径在单页面应用中是没有的
服务器需要增加所有情况的候选资源,让它们都返回同一个index.html文件
  • 全局组件
<router-view>
<router-link :to="{path: 'apple', query: {color: 'red' }}">
<router-link :to="{name: 'applename', params: { color: 'red' }}">

单个路由配置、动态路由匹配、动态添加路由配置

  • 单个路由配置
{
   path: '/user/:id',//path是地址栏#后面的东西
   props:true,//可以将路由的参数作为属性传递到组件中
   name: 'user',//有name时,当前路由变成唯一的了
   component: User,
   component: () => import('../views/User.vue'),//延迟加载(用到的时候加载)
   redirect: '/home',//重定向
   children:[
       {
          path: 'collection',// 主路由上的path会被自动添加到子路由之前
          name: 'collection',
          component: Collection
        }, 
   ]
}
  • 动态路由匹配
- 使用场景	
同一个组件,路径参数一样,展示有所不同

- 匹配模式、匹配路径、参数获取
匹配模式:/users/:username			/users/:username/:userid
匹配路径:/users/jim						/users/jim/123
参数获取:route.params.username		route.params.userid
  • 动态添加路由配置
let routesA = [
    {path:'/aList',component:AList},
    {path:'/aDetail',component:ADetail},
]
if(role == 'A'){
    router.addRoutes(routesA)
}

导航

  • 声明式
<router-ling to="">
  • 编程式
push 、replace 、 go(n)  
router.push({path: '/detail', query:{}})
router.push({name: 'detail', params:{}}) // 这里的name对应路由配置中的name,大小写敏感
// 使用参数
route.query.xx
route.params.xx

路由守卫

  • 守卫参数
1、to 将要进入的路由
2、from 当前导航正要离开的路由
3、next 表示放行,必须严格保证该方法起码被调用一次,易出现死循环的现象
next()    next({name: 'detail'})     next({path: '/detail'})
  • 全局守卫
- beforeEach
- afterEach
  • 路由中的守卫
    {
        path:'/home',
        component: Home,
        beforeEnter:(to,from,next)=>{...}
    }
  • 组件中的守卫
beforeRouteEnter:进入组件时
beforeRouteUpdate:路由不变,传递的参数改变
beforeRouteLeave: 离开组件前

相关推荐

  1. vue使用

    2024-03-31 06:02:04       43 阅读
  2. Vue中嵌套(子)的使用

    2024-03-31 06:02:04       35 阅读
  3. Vue使用

    2024-03-31 06:02:04       62 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 06:02:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 06:02:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 06:02:04       82 阅读
  4. Python语言-面向对象

    2024-03-31 06:02:04       91 阅读

热门阅读

  1. 小米汽车:驶向未来的科技新星

    2024-03-31 06:02:04       39 阅读
  2. 专升本-机器人流程化自动化(RPA)

    2024-03-31 06:02:04       37 阅读
  3. Kafka开机自启脚本

    2024-03-31 06:02:04       41 阅读
  4. vector和array区别

    2024-03-31 06:02:04       39 阅读
  5. IPv6 Scapy Samples

    2024-03-31 06:02:04       35 阅读
  6. 2024-03-30 问AI: 介绍一下深度学习里面的 DCNN模型

    2024-03-31 06:02:04       43 阅读
  7. WebStorm 与 VSCode 对比分析

    2024-03-31 06:02:04       39 阅读