路由(Routing)是指确定网站或应用程序中特定页面的方式。在Web开发中,路由用于根据URL的不同部分来确定应用程序中应该显示哪个内容。
- 构建前端项目
js
npm init vue@latest
//或者
npm init vite@latest
- 安装依赖和路由
js
npm install
npm install vue-router -S

- router 使用
login.vue
html
<template>
<div>
<div class="login">login</div>
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
.login {
background-color: red;
height: 400px;
width: 400px;
font-size: 20px;
color: white;
}
</style>
reg.vue
html
<template>
<div>
<div class="reg">reg</div>
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
.reg {
background-color: green;
height: 400px;
width: 400px;
font-size: 20px;
color: white;
}
</style>
index.ts
ts
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
component: () => import("../components/login.vue")
},
{
path: "/reg",
component: () => import("../components/reg.vue")
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
App.vue
html
<template>
<h1>hello world</h1>
<div>
<router-link to="/">Login</router-link>
<router-link style="margin: 10px;" to="/reg">Reg</router-link>
</div>
<hr>
<router-view></router-view>
</template>
<script setup lang="ts">
</script>
<style scoped>
</style>
main.ts
ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')

