路由(Routing)是指確定網站或應用程序中特定頁面的方式。在Web開發(fā)中,路由用于根據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")
}
]
// 創(chuàng)建路由器
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')
router-view
補充:
router-view
是Vue Router提供的一個組件,用于在Vue應用中展示匹配到的路由組件。
在Vue應用的模板中,可以使用<router-view></router-view>
標簽來放置router-view
。當訪問的路徑與路由配置中定義的路由匹配時,對應的路由組件將顯示在router-view
的位置。
以下是一個簡單的示例:
<template>
<div>
<h1>My App</h1>
<router-view></router-view>
</div>
</template>
在上述例子中,<router-view></router-view>
的位置就是用于展示匹配到的路由組件的地方。當用戶訪問的路徑匹配到了某個路由配置,對應的路由組件將會顯示在<router-view>
標簽的位置。文章來源:http://www.zghlxwxcb.cn/news/detail-646052.html
通過使用<router-view>
,我們可以根據不同的路徑加載不同的路由組件,從而實現(xiàn)頁面的動態(tài)切換。文章來源地址http://www.zghlxwxcb.cn/news/detail-646052.html
到了這里,關于【Vue-Router】路由入門的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!