vite+vue+ts+element-plus从零开发管理后台框架(03)-路由

新建视图

新建src/views/Login.vue,内容如下。

<template>
    这是登录页
</template>

新建src/views/Main.vue,内容如下。

<template>
    这是主页
</template>

新建src/views/errors/404.vue,内容如下。

<template>
    404 page not found
</template>

编辑src/App.vue,内容如下。

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

路由配置

安装组件

npm install vue-router@4.4.0

新建src/router/index.ts,内容如下。

import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'


const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
    },
    {
        path: '/',
        name: 'Main',
        component: () => import('@/views/Main.vue'),
    },
    {
        path: '/:catchAll(.*)',
        component: () => import('@/views/errors/404.vue'),
    },
]

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


export default router

编辑src/main.ts,导入并使用路由。

import App from './App.vue'

import router from './router'
app.use(ElementPlus).use(router)

测试

浏览器访问 localhost:5173/#/login 网页会显示这是登录页

浏览器访问 localhost:5173/#/ 网页会显示这是主页

浏览器访问 localhost:5173/#/xxx 或其他任意不存在的路由网页都会显示404 page not found

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!