今日讲讲路由配置

下载安装路由

  1. 下载安装路由库
    npm i vue-router

  2. 在 src 中新建 views 文件夹,在其中新建页面

  3. 在 src 中新建一个 router 文件夹,其中新建一个 index.js

    import { createRouter, createWebHashHistory } from 'vue-router';
    // 导入页面
    import index from '../views/index.vue';
    import about from '../views/about.vue';
    // 注册
    const routes = [
    {
    path: '/', // 路径名,首页是/
    name: 'index', // 页面名
    component: index, // 组件,页面对应的文件
    },
    {
    path: '/about',
    name: 'about',
    component: about,
    },
    ];
    // 路由实例
    const router = createRouter({
    history: createWebHashHistory(),
    routes, // 所有的路由
    });
    // 导出
    export default router;

  4. 在 main.js 中安装路由

    import { createApp } from 'vue'
    import App from './App.vue'
    // 导入路由实例
    import router from './router';
    // vue实例
    const app = createApp(App)
    // 在vue实例上安装路由
    app.use(router)
    app.mount('#app')

  5. 在 App.vue 中写出口

    <template> <router-view></router-view> </template>

路由模式

模式有两种: h5 、 hash

复制代码
h5: createWebHistory;http://localhost:5173/about;刷新404

hash:createWebHashHistory;http://localhost:5173/#/about

捕获404页面

  1. 新建一个 404 页面( NotFound )

  2. 导入页面

  3. 在配置数组中添加如下:

    { path: '/:pathMatch(.)', name: 'NotFound', component: NotFound },

重定向

使用redirect属性

复制代码
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
redirect: '/'
},
相关推荐
MrGud4 分钟前
Cesium中的坐标系及其转换
前端·cesium
小付学代码4 分钟前
香港地图可编辑版
前端
兆子龙16 分钟前
TypeScript高级类型编程:从入门到精通
前端·后端
SuperEugene19 分钟前
Vue3 模板语法规范实战:v-if/v-for 不混用 + 表达式精简,避坑指南|Vue 组件与模板规范篇
开发语言·前端·javascript·vue.js·前端框架
IT_陈寒25 分钟前
Python开发者的效率革命:这5个技巧让你的代码提速50%!
前端·人工智能·后端
Luna-player26 分钟前
Vue 3 + Vue Router 的路由配置,简单示例
前端·javascript·vue.js
用户693717500138426 分钟前
不卷AI速度,我卷自己的从容——北京程序员手记
android·前端·人工智能
xiaotao13133 分钟前
03. 原子化 CSS 思想
前端·css·tailwind
敲代码的约德尔人37 分钟前
JavaScript 设计模式完全指南
javascript·设计模式