vue-router 解析

        Vue Router 是 Vue.js 的官方路由,它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举,今天主要记录一下vue-router的使用。

目录

一、创建路由器

二、静态路由和动态路由

三、嵌套路由

四、命名路由

五、命名视图

 六、路由元信息

七、导航守卫

八、滚动行为


一、创建路由器

路由器实例是通过调用createRouter函数创建的:

const routes: Array<RouteRecordRaw> = []

const router = createRouter({
  history: createWebHistory(),
  routes
})

//在main.ts文件中添加
createApp(App)
  .use(router)
  .mount('#app')

创建路由模式分为Hash 模式、Memory 模式和HTML5 模式:

  • createWebHashHistory:在URL之前添加#,在浏览器中添加历史记录;
  • createMemoryHistory:不会添加历史记录,主要考虑在无痕模式下使用;
  • createWebHistory:正常URL,在浏览器中添加历史记录;

路由器访问: 在组件模板中,路由器实例暴露$router,当前路由暴露$route;在选项api中,路由器实例暴露useRouter(),当前路由暴露useRoute();

重定向:redirect,redirect值可以是string,object也可以是function,动态返回重定向目标

区分大小写:sensitive,默认false,不区分路径大小写,true,区分大小写

prop:值可以为:boolean:默认false,true则会将参数作为prop传递给组件;object:主要是添加静态数据,把静态数据作为prop传递给组件;function:可以把静态数据和路由携带参数结合在作为prop传递给组件

匹配路径结尾'/':strict,默认false,结尾可以带‘/’;true,结尾不能带‘/’;该字段是createRouter中的一个全局属性

二、静态路由和动态路由

静态路由

import HomeView from '../views/HomeView.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/home',
    component:HomeView
  }
]

//或者
const routes: Array<RouteRecordRaw> = [
  {
    path: '/home',
    component: () => import(/* webpackChunkName: "home" */ '../views/HomeView.vue')
  }
]

动态路由

  {
    path: '/about/:id',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },

 以上可匹配路径:/about/1,/about/a;

路径映射到$route.params对应相应的字段

匹配模式匹配路径route.params

/about/:id

/about/1

{id:1}

路由匹配规则

  {
    path: '/about/:id',//可匹配:/about/a  匹配结果:params:{id:a}
    path:'/about/:id(\\d+)',//仅匹配数字:/about/1  匹配结果:params:{id:1}
    path:'/about/:id?',//可匹配:/about,/about/1 匹配结果:params:{id:''} ,params:{id:1}
    path: '/about/:id+',//可匹配:/about/a,/about/a/b  匹配结果:params:{id:['a']},params:{id:['a','b']}
    path: '/about/:id*',//可匹配:/about,/about/a,/about/a/b  匹配结果:params:{id:[]} ,params:{id:['a']} ,params:{id:['a','b']}
  },

说明:id后面不添加其他符合,则只能匹配当前一级;添加?,则可以不传参,或者匹配一级参数;添加+,则必须传参,可以匹配多级参数;添加*,则可以不传参数,可以匹配多级参数;以上是常用的匹配语法,还可以添加正则表达式,可以根据需求自行尝试。

三、嵌套路由

嵌套路由分为2种:1、子组件嵌套到父组件中,这种情况,父组件要包含router-view,这样子组件才会在父组件中显示;2、子组件和父组件只保留父子关系 ,在页面跳转中,只使用子路由组件,父组件不包含component 和 components,多用于分组等

例如:

//第一种
{
    path: '/',
    name: 'home',
    component: HomeView,
    children:[
      {
        path: 'child',
        component: ChildrenView,
      },
    ]
  }

//第二种
{
    path: '/',
    name: 'home',
    children:[
      {
        path: 'child',
        component: ChildrenView,
      },
    ]
  }

四、命名路由

创建路由时,可以为路由添加name属性,该属性是全局唯一,如果存在多个,则取最后一个。

路由跳转可以使用name属性:

router.push({ name: 'user'})
//或者
<router-link :to="{ name: 'user'}" />

五、命名视图

同级展示多个视图,非嵌套视图,可以在单页面中使用多个视图,如果router-view未使用名称,则默认为default

  <router-view ></router-view>  
  <router-view name="ContentView"></router-view>
  <router-view name="IndexView"></router-view> 


//创建路由
import HomeView from '../views/HomeView.vue'
import IndexView from '../views/index.vue'
import ContentView from '../views/content.vue'
 {
    path: '/',
    components:{
      default:HomeView,
      ContentView,
      IndexView
    }
  }

也可以使用命名视图创建复杂的嵌套命名视图,例如:

<div class="container">
    <router-view></router-view>
    <router-view name="ContentView"></router-view>
  </div>

//创建路由
import IndexView from '../views/index.vue'
import ContentView from '../views/content.vue'

{
    path: '/main',
    name: 'main',
    component: () => import(/**webpackChunkName: "main" */ '../views/main.vue'),
    children: [
      {
        path: 'nav',
        components: {
          default: IndexView,
          ContentView
        }
      }
    ]
  },

 六、路由元信息

declare module 'vue-router'{
  interface RouteMeta{
    isIcon?:Boolean;
    isAuth?:Boolean;
  }
}

 可以继承来自 vue-router 中的 RouteMeta 来为 meta 字段添加自定义字段

七、导航守卫

 全局前置守卫router.beforeEach

router.beforeEach((to,from,next) =>{
  //这里是否需要验证登录
  if(to.meta.isAuth !== undefined && !to.meta.isAuth){
    next()
  }else{
    //判断验证权限
    next()
  }
})

全局后置钩子router.afterEach

router.afterEach(() =>{
  //页面跳转后,处理事件
})

八、滚动行为

注意: 这个功能只在支持 history.pushState 的浏览器中可用。

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置 例如:return {top:0,left:0,el:''};如果el(css选择器或者dom元素)存在,则left,top相对该元素的偏移量,el不存在则相对当前页面
  }
})

savedPosition:只有触发浏览器前进、后退才会有返回,该字段是保存页面滚动位置

 以上是关于vue-router常用方法说明,想了解其他的可以查看Vue Route 官网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

travel_wsy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值