今日讲讲路由配置

下载安装路由

  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: '/'
},
相关推荐
天若有情6732 分钟前
【C++原创开源】formort.h:一行头文件,实现比JS模板字符串更爽的链式拼接+响应式变量
开发语言·javascript·c++·git·github·开源项目·模版字符串
天***88525 分钟前
Edge 浏览器离线绿色增强版+官方安装包,支持win7等系统
前端·edge
漫游的渔夫14 分钟前
别再直接 `json.loads` 了!AI 返回的 JSON 坑位指南
前端·人工智能
软件工程师文艺25 分钟前
从0到1:Claude Code如何用React构建CLI应用
前端·react.js·前端框架
M ? A35 分钟前
Vue 迁移 React 实战:VuReact 一键自动化转换方案
前端·vue.js·经验分享·react.js·开源·自动化·vureact
yuki_uix36 分钟前
重排、重绘与合成——浏览器渲染性能的底层逻辑
前端·javascript·面试
Burt1 小时前
我的 2026 全栈选型:Vue3 + Elysia + Bun + AlovaJS
vue.js·全栈·bun
止观止1 小时前
拥抱 ESNext:从 TC39 提案到生产环境中的现代 JS
开发语言·javascript·ecmascript·esnext
沃尔威武1 小时前
调试黑科技:Chrome DevTools时间旅行调试实战
前端·科技·chrome devtools
小锋java12341 小时前
SpringBoot 4 + Spring Security 7 + Vue3 前后端分离项目设计最佳实践
java·vue.js·spring boot