程序员的知识教程库

网站首页 > 教程分享 正文

小白从0搭建 Vite5 + Vue3 轮子:2. 使用vue-router 4.x

henian88 2024-10-10 05:54:36 教程分享 9 ℃ 0 评论

一 安装依赖

在命令行(Windows PowerSell)中,输入:npm i vue-router -D,回车安装。

输入 npm list 回车查看已经安装的依赖


二 添加两个路由页面 a.vue 和 b.vue

在项目文件夹中的 src 目录中新建 view 目录,后在 view 的目录中建立 test 目录,最后在 test 目录中建立 a.vue 和 b.vue 文件。

a.vue

<template>
    <div>
        <p>a.vue</p>
        <p>+ + + + +</p>
    </div>
</template>

b.vue

<template>
    <div>
        <p>b.vue</p>
        <p>+ + + + +</p>
    </div>
</template>


三 添加路由配置文件 test.js 和 路由入口 index.js

在 /src 目录中新建 router 目录用来放置路由配置文件,后在 router 目录中添加 test.js 路由配置文件和 index.js 路由入口文件。

/src/router/test.js

// 路由懒加载
const pA = () => import('/src/view/test/a.vue')
const pB = () => import('/src/view/test/b.vue')

const testRoutes = [
     {
        path: '/a',
        name: 'a',
        meta: {
            title: 'a',
        },
        component: pA,
     },
     {
        path: '/b',
        name: 'b',
        meta: {
            title: 'b',
         },
        component: pB,
     },
     {
        path: '/:pathMatch(.*)*',
        redirect: '/a', //404跳转到/a
     },
]
export default testRoutes

/src/router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import testRoutes from './test.js'
const router = createRouter({
    history: createWebHistory(),
    routes: testRoutes,
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
    window.document.title = to.meta.title
    next()
})
//全局后置钩子
router.afterEach((to, from) => {
    window.scrollTo(0, 0)	
})
export default router


四 修改项目入口文件/src/mian.js,将路由入口文件全局引入

/src/main.js

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'

// createApp(App).mount('#app')
const app = createApp(App)
// 引用路由
app.use(router)
app.mount('#app')


五 将/src/App.vue文件改为:

<template>
    <main>
        <nav class="nav">
            <!-- 
            <a href="/a">a.vue</a>
             <a href="/b">b.vue</a>
            -->
            <router-link to="/a" tab="li">a.vue</router-link>
            <router-link to="/b" tab="li">b.vue</router-link>
        </nav>
        <router-view></router-view>
    </main>
</template>

<style scoped>
.nav {
    margin-bottom: 30px;
    border-bottom: 1px solid #cccccc;
}
.nav a {
		margin: 0 20px;
}
</style>


六 启动测试

命令行中输入:npm run dev,在浏览器中输入网址:http://localhost:8080,
分别点击 a.vue / b.vue 查看


vue-router 配置的参考网址:https://router.vuejs.org/zh/

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表