一、Vue3.x中的路由
路由可以讓應(yīng)用程序根據(jù)用戶輸入的不同地址動(dòng)態(tài)掛載不同的組件。
https://next.router.vuejs.org/
npm install vue-router@next --save
二、Vue3.x路由的基本配置
1、安裝路由模塊
npm install vue-router@next --save
2、新建組件
components/Home.vue
<template>
<div>
Home組件
</div>
</template>
<script lang="ts">
import {
defineComponent,
} from 'vue';
export default defineComponent({
name: 'Home',
});
</script>
<style>
</style>
components/News.vue
<template>
<div>
News組件
</div>
</template>
<script lang="ts">
import {
defineComponent,
} from 'vue';
export default defineComponent({
name: 'News',
});
</script>
<style>
</style>
3、配置路由
新建src/routes.ts 配置路由
import {createRouter,createWebHashHistory} from 'vue-router'
import Home from "./components/Home.vue"
import News from "./components/News.vue"
const router = createRouter({
// 4\. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/news', component: News }
],
})
export default router
4、掛載路由
在main.ts中掛載路由
import { createApp } from 'vue'
import App from './App.vue'
import router from './routes'
// createApp(App).mount('#app')
const app = createApp(App)
//掛載路由
app.use(router)
app.mount('#app')
5、渲染組件
App.vue中通過router-view渲染組件
<template>
<ul>
<li>
<router-link to="/">首頁</router-link>
</li>
<li>
<router-link to="/news">新聞</router-link>
</li>
</ul>
<router-view></router-view>
</template>
<script lang="ts">
import {
defineComponent
} from 'vue';
export default defineComponent({
name: 'App',
});
</script>
<style>
</style>
三、Vue3.x動(dòng)態(tài)路由
1、配置動(dòng)態(tài)路由
const router = createRouter({
// 4\. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/news', component: News },
{ path: '/newsContent/:id', component: NewsContent },
],
})
2、路由跳轉(zhuǎn)
<li v-for="(item,index) in list" :key="index">
<router-link :to="`/newsContent/${index}`">{{item}}</router-link>
</li>
3、獲取路由
this.$route.params
四、Vue3.x Get傳值
<router-link to="/newsContent?id=2">Get傳值</router-link>
this.$route.query
五、Vue3.x路由編程式導(dǎo)航(Js跳轉(zhuǎn)路由)
this.$router.push({ path: 'news' })
this.$router.push({
path: '/newsContent/495'
});
this.$router.push({ path: '/newscontent', query:{aid:14} }
this.$router.push({ path: '/newscontent/123'})
六、Vue3.x路由HTML5 History 模式和 hash 模式
6.1、 hash 模式
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
//...
],
})
http://localhost:8080/#/user
http://localhost:8080/#/news
如果想把上面的路由改變成下面方式:
http://localhost:8080/news
http://localhost:8080/user
我們就可以使用HTML5 History 模式
6.2、 HTML5 History 模式
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
//...
]
})
注意:開啟Html5 History模式后,發(fā)布到服務(wù)器需要配置偽靜態(tài):
https://router.vuejs.org/zh/guide/essentials/history-mode.html
七、Vue3.x命名路由
有時(shí)候,通過一個(gè)名稱來標(biāo)識(shí)一個(gè)路由顯得更方便一些,特別是在鏈接一個(gè)路由,或者是執(zhí)行一些跳轉(zhuǎn)的時(shí)候。你可以在創(chuàng)建 Router 實(shí)例的時(shí)候,在 routes 配置中給某個(gè)路由設(shè)置名稱。
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})
要鏈接到一個(gè)命名路由,可以給 router-link 的 to 屬性傳一個(gè)對(duì)象:
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
這跟代碼調(diào)用 router.push() 是一回事:
this.$router.push({ name: 'user', params: { userId: 123 }})
這兩種方式都會(huì)把路由導(dǎo)航到 /user/123 路徑。
this.$router.push({name:'content',query:{aid:222}})
八、路由重定向
重定向也在routes配置中完成。要從重定向/a到/b:
const routes = [{ path: '/home', redirect: '/' }]
重定向也可以針對(duì)命名路由:
const routes = [{ path: '/home', redirect: { name: 'homepage' } }]
甚至使用函數(shù)進(jìn)行動(dòng)態(tài)重定向:
const routes = [
{
// /search/screens -> /search?q=screens
path: '/search/:searchText',
redirect: to => {
// the function receives the target route as the argument
// we return a redirect path/location here.
return { path: '/search', query: { q: to.params.searchText } }
},
},
{
path: '/search',
// ...
},
]
相對(duì)重定向
也可以重定向到相對(duì)位置:
const routes = [
{
path: '/users/:id/posts',
redirect: to => {
// the function receives the target route as the argument
// return redirect path/location here.
},
},
]
九、路由別名
重定向是指用戶訪問時(shí)/home,URL將被替換/,然后與匹配/。但是什么是別名?
別名/as/home表示用戶訪問時(shí)/home,URL保持不變/home,但將被匹配,就像用戶正在訪問時(shí)一樣/。
以上內(nèi)容可以在路由配置中表示為:
const routes = [{ path: '/', component: Homepage, alias: '/home' }]
別名使您可以自由地將UI結(jié)構(gòu)映射到任意URL,而不受配置的嵌套結(jié)構(gòu)的約束。使別名以a開頭,/以使路徑在嵌套路由中是絕對(duì)的。您甚至可以將兩者結(jié)合起來,并為數(shù)組提供多個(gè)別名:
const routes = [
{
path: '/users',
component: UsersLayout,
children: [
// this will render the UserList for these 3 URLs
// - /users
// - /users/list
// - /people
{ path: '', component: UserList, alias: ['/people', 'list'] },
],
},
]
如果您的路線包含參數(shù),請(qǐng)確保將其包含在任何絕對(duì)別名中:
const routes = [
{
path: '/users/:id',
component: UsersByIdLayout,
children: [
// this will render the UserDetails for these 3 URLs
// - /users/24
// - /users/24/profile
// - /24
{ path: 'profile', component: UserDetails, alias: ['/:id', ''] },
],
},
]
十、嵌套路由

配置News組件的子組件
1、新建news/Add.vue
<template>
<div>
增加新聞
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
data(){
return{}
},methods:{
}
})
</script>
2、新建news/Edit.vue
<template>
<div>
修改新聞
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
data(){
return{
}
},methods:{
}
})
</script>
3、配置嵌套路由
import { createRouter, createWebHistory } from 'vue-router'
//引入組件
import Home from "./components/Home.vue"
import News from "./components/News.vue"
import NewsAdd from "./components/News/Add.vue"
import NewsEdit from "./components/News/Edit.vue"
import User from "./components/User.vue"
//配置路由
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home, alias: '/home' },
{
path: '/news', component: News,
children: [ //子路由
{ path: '', redirect:"/news/add"},
{ path: 'add', component: NewsAdd },
{ path: 'edit', component: NewsEdit },
]
},
{ path: '/user', component: User },
],
})
export default router
4、News.vue中掛載路由
<template>
<div class="content">
<div class="left">
<ul>
<li><router-link to="/news/add">增加新聞</router-link></li>
<li><router-link to="/news/edit">修改新聞</router-link></li>
</ul>
</div>
<div class="right">
<router-view></router-view>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
data() {
return {};
},
});
</script>
<style lang="scss">
.content {
display: flex;
padding: 20px;
.left {
width: 200px;
border-right: 1px solid #ddd;
min-height: 400px;
}
.right {
flex: 1;
}
}
</style>