### 一、Vue3.x中的路由
路由可以讓應用程序根據用戶輸入的不同地址動態掛載不同的組件。
[https://next.router.vuejs.org/](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動態路由
**1、配置動態路由**
~~~
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、路由跳轉**
~~~
<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路由編程式導航(Js跳轉路由)
~~~
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模式后,發布到服務器需要配置偽靜態:
[https://router.vuejs.org/zh/guide/essentials/history-mode.html](https://router.vuejs.org/zh/guide/essentials/history-mode.html)
### 七、Vue3.x命名路由
有時候,通過一個名稱來標識一個路由顯得更方便一些,特別是在鏈接一個路由,或者是執行一些跳轉的時候。你可以在創建 Router 實例的時候,在 `routes` 配置中給某個路由設置名稱。
~~~
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})
~~~
要鏈接到一個命名路由,可以給 `router-link` 的 `to` 屬性傳一個對象:
~~~
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
~~~
這跟代碼調用 `router.push()` 是一回事:
~~~
this.$router.push({ name: 'user', params: { userId: 123 }})
~~~
這兩種方式都會把路由導航到 `/user/123` 路徑。
~~~
this.$router.push({name:'content',query:{aid:222}})
~~~
### 八、路由重定向
重定向也在`routes`配置中完成。要從重定向`/a`到`/b`:
~~~
const routes = [{ path: '/home', redirect: '/' }]
~~~
重定向也可以針對命名路由:
~~~
const routes = [{ path: '/home', redirect: { name: 'homepage' } }]
~~~
甚至使用函數進行動態重定向:
~~~
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',
// ...
},
]
~~~
#### 相對重定向
也可以重定向到相對位置:
~~~
const routes = [
{
path: '/users/:id/posts',
redirect: to => {
// the function receives the target route as the argument
// return redirect path/location here.
},
},
]
~~~
### 九、路由別名
重定向是指用戶訪問時`/home`,URL將被替換`/`,然后與匹配`/`。但是什么是別名?
**別名`/`as`/home`表示用戶訪問時`/home`,URL保持不變`/home`,但將被匹配,就像用戶正在訪問時一樣`/`。**
以上內容可以在路由配置中表示為:
~~~
const routes = [{ path: '/', component: Homepage, alias: '/home' }]
~~~
別名使您可以自由地將UI結構映射到任意URL,而不受配置的嵌套結構的約束。使別名以a開頭,`/`以使路徑在嵌套路由中是絕對的。您甚至可以將兩者結合起來,并為數組提供多個別名:
~~~
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'] },
],
},
]
~~~
如果您的路線包含參數,請確保將其包含在任何絕對別名中:
~~~
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>
~~~
- 空白目錄
- 第一節 Vue3.x教程、Vue3.x簡介、搭建Vue3.x環境、創建運行Vue3.x項目、分析Vue目錄結構
- 第二節 Vue3.x綁定數據、綁定html、綁定屬性、循環數據
- 第三節 Vue3.x中的事件方法入門、模板語法模板中類和樣式綁定
- 第四節 Vue3.x中的事件方法詳解、事件監聽、方法傳值、事件對象、多事件處理程序、事件修飾符、按鍵修飾符
- 第五節 Vue3.x中Dom操作$refs 以及表單( input、checkbox、radio、select、 textarea )結合雙休數據綁定實現在線預約功能
- 第六節 Vue3.x中使用JavaScript表達式 、條件判斷、 計算屬性和watch偵聽
- 第七節 Vue3.x 實現一個完整的toDoList(待辦事項) 以及類似京東App搜索緩存數據功能
- 第八節 Vue3.x中的模塊化以及封裝Storage實現todolist 待辦事項 已經完成的持久化
- 第九節 Vue3.x中的單文件組件 定義組件 注冊組件 以及組件的使用
- 第十節 Vue3.x父組件給子組件傳值、Props、Props驗證、單向數據流
- 第十一節 Vue3.x父組件主動獲取子組件的數據和執行子組件方法 、子組件主動獲取父組件的數據和執行父組件方法
- 第十二節 Vue3.x組件自定義事件 以及mitt 實現非父子組件傳值
- 第十三節 Vue3.x自定義組件上面使用v-mode雙休數據綁定 以及 slots以及 Prop 的Attribute 繼承 、禁用 Attribute 繼承
- 第十四節 Vue3.x中組件的生命周期函數(lifecycle)、 this.$nextTick、動態組件 keep-alive、Vue實現Tab切換
- 第十五節 Vue3.x中全局綁定屬性、使用Axios和fetchJsonp請求真實api接口數據、函數防抖實現百度搜索
- 第十六節 Vue3.x中的Mixin實現組件功能的復用 、全局配置Mixin
- 第十七節 Vue3.x Teleport、使用Teleport自定義一個模態對話框的組件
- 第十八節 Vue3.x Composition API 詳解
- 第十九節 Vue3.x中集成Typescript 使用Typescript
- 第二十節 Vue-Router 詳解
- 第二十節 Vuex教程-Vuex 中的 State Mutation Getters mapGetters Actions Modules