路由(Routing)是指确定网站或应用程序中特定页面的方式。在Web开发中,路由用于根据URL的不同部分来确定应用程序中应该显示哪个内容。
- 构建前端项目
npm init vue@latest
//或者
npm init vite@latest
- 安装依赖和路由
npm install
npm install vue-router -S
3. router 使用
login.vue
<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
<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
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
<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
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')