【Vue Router】005-命名路由

1.5 命名路由

1.5.1 概述

有时候通过一个名字来标识路由会更方便,特别是在链接到路由,或者执行导航时。在创建 Router 实例的时候,在 routes 选项中为路由设置名称。

1.5.2 基本写法

修改 index.js 文件

import { createRouter, createWebHashHistory } from 'vue-router'
import Study from '../views/Study.vue'
import Home from '../views/Home.vue'
import News from '../views/News.vue'
import Books from '../views/Books.vue'
import Videos from '../views/Videos.vue'
import Book from '../views/Book.vue'
const routes = [
  {
    path: '/',
    component: Study,
    name: 'study',
    // 这里使用 name 指定重定向的目标
    redirect: {
      name: 'news'
    },
    children: [
      {
        path: '/home',
        name: 'home',
        component: Home
      }, {
        path: '/news',
        name: 'news',
        component: News
      }, {
        // 本来我们就使用嵌套路由了,咋这里我们再次向下嵌套
        path: '/books',
        name: 'books',
        component: Books,
        children: [
          { path: '/book/:id', name: 'book', component: Book }
        ]
      }, {
        path: '/videos',
        name: 'videos',
        component: Videos
      }
    ]
  }
]

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

export default router

1.5.3 另外两种重定向的方法

方法一:指定目标路径

{
    path: '/'.
    // 指定目标路径
    redirect: '/news'
}

方法二:使用函数动态重定向

{
    // /search/screens -> /search?q=screens
    path: '/search/:searchText',
    // 函数接收路由作为参数,动态返回重定向目标
    // 返回值可以是重定向的字符串路径或路径对象
    redirect: to => {
        return { path: '/search', query: { q: to.params.searchText } }
    }
}

1.5.4 在设置导航链接时使用命名路由

修改 Study.vue,注意 to 前面需要带 : ,:to

<template>
  <router-link to="/">主页</router-link>
  <router-link :to="{ name: 'news' }">新闻</router-link>
  <router-link :to="{ name: 'books' }">图书</router-link>
  <router-link :to="{ name: 'videos' }">视频</router-link>
  <div>=================</div>
  <router-view />
</template>

<script>
export default {
  el: 'Study'
}
</script>

<style>
</style>

1.5.5 在设置导航链接时使用命名路由的传参数写法

这里仅作写法展示,实际项目中需要修改路由配置 index.js 文件,使得能够接收参数即可,前面有案例

<router-link :to="{ name: 'news', params: {id: book.id} }">新闻</router-link>

1.5.6 在路由配置中给某个路径起个别名

截取 index.js 中的片段进行演示

{
    path: '/news',
    name: 'news',
    component: News,
    alias: '/xinwen' // 给 news 起个别名 /xinwen
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值