vue动态路由及案例

本文介绍了Vue中的动态路由概念,包括动态路由的定义和写法,强调了动态路由参数在组件内的使用。同时,讲解了如何设置404捕获页面,以及通配符路由的注意事项,提供了一个具体的动态路由配置和404页面处理的案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在此之前遇到的都是一个路径对应一个组件的情况,但有时我们会遇到多个路径对应一个组件的情况。

比如个人中心对应一个 User 组件,学员登录个人中心时,由于大家的 id 各不相同,所以个人中心的路径可能会不同,像 /user/123、/user/456 这样,但其实页面会使用同一个 User 组件来渲染。

这里的 123和456 指的是用户 id,也就是在路径中添加的参数。

像这种多个路径都映射到一个组件这种情况就属于动态路由。

动态路由

动态路由即符合某种模式的多个路径映射到同一个组件,动态路由的写法:

import User from "./views/User.vue";

const routes = [
  // id 就是路径参数
  { path: '/user/:id', component: User }
]

id 为路径参数,一个“路径参数”前需要使用冒号 : 标记。
当 url 匹配到路由中的一个路径时,参数值会被设置到 this.$route.params 里,可以在组件内读取到。
比如 /user/456 匹配的就是 /user/:id,那么这个用户的 id 就是 456,this.$route.params.id 的值就是 456。

现在我们在 User 的模板,输出当前用户的 id:

<template>
  <div>user id: {{ $route.params.id }}</div>
</template>

捕获 404 页面

当用户输入的 url 不属于我们注册的任何一个路由时,我们常需要将页面用 404 NotFound 组件渲染,这里我们可以用通配符(*)来匹配任意路径:

import NotFound from "./views/NotFound.vue";

const routes = [
  {
    // 会匹配所有路径
    path: '*',
    component: NotFound
  }
]

当使用通配符路由时,请确保含有通配符的路由应该放在最后。因为路由的匹配通常是根据注册的顺序匹配的,如果 path: ‘*’ 路由放在最前面,那么所有的页面都会因为先匹配到通配符路由而由 NotFound 组件渲染。

如何读取匹配到的路径值

当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 的参数。
它包含了 URL 通过通配符被匹配的部分,比如用上面的路由 { path: ‘*’ } 匹配 URL http://localhost:8081/non-existing/file:

this.$route.params.pathMatch // '/non-existing/file'

案例:
router/index.js

// 0. 使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
import Layout from '../views/Layout.vue';
import Home from '../views/Home.vue';
import CourseAll from '../views/CourseAll.vue';
import CourseDetail from '../views/CourseDetail.vue';
import NotFound from '../views/NotFound.vue';

// 2. 定义路由
const routes = [
  {
    path: '/layout',
    component: Layout,
    children: [
      { path: 'home', component: Home },
      { path: 'courseall', component: CourseAll },
      { path: 'coursedetail/:courseId', component: CourseDetail }
    ]
  },
  {
    path: '*',
    component: NotFound
  }
];

// 3. 创建 router 实例,然后传 `routes` 配置
export default new VueRouter({
  mode: 'history',
  routes // (缩写) 相当于 routes: routes
});

// 4. 在 main.js 中创建和挂载根实例

views/CourseDetail.vue

<template>
  <div class="page-coursedetail">
    <div class="banner"></div>
    <div class="detail">
      <div class="title">{{course && course.title}}</div>
      <div class="desc">{{course && course.desc}}</div>
    </div>
    <button class="btn-buy">加入购物清单</button>
  </div>
</template>

<script>
export default {
  name: 'CourseAll',
  data: function() {
    return {
      courseList: [
        {
          id: 'f1',
          title: 'Web前端基础',
          desc:
            '本课程通过HTML、CSS基础的学习,带领大家掌握Web前端基础。'
        },
        {
          id: 'f2',
          title: 'Web前端进阶',
          desc:
            '本课程是对基础课程的补充和提升,补充了一些CSS进阶知识,结合丰富的小练习来夯实基础。'
        }
      ]
    };
  },
  computed: {
    course() {
      return this.courseList.find(course => course.id === this.$route.params.courseId) || {}
    }
  }
};
</script>

<style lang="scss" scoped>
.page-coursedetail {
  padding-top: 70px;
  .banner {
    width: 335px;
    height: 120px;
    margin: 0 auto;
    background: #2c3744;
    border-radius: 8px;
  }
  .detail {
    width: 335px;
    margin: 0 auto;
    text-align: left;
    .title {
      padding-top: 15px;
      font-weight: 500;
      font-size: 20px;
      line-height: 28px;
      color: #ffffff;
    }
    .desc {
      padding-top: 10px;
      font-size: 15px;
      line-height: 21px;
      color: #ffffff;
    }
  }
  .btn-buy {
    width: 335px;
    height: 46px;
    margin: 0 auto;
    margin-top: 20px;
    background: #3ab599;
    border: none;
    border-radius: 4px;
    font-weight: 500;
    font-size: 15px;
    color: #ffffff;
    box-sizing: border-box;
    &:focus {
      outline: none;
    }
  }
}
</style>

<style lang="scss">
html {
  background: #17191D;
}
</style>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值