Vue3中的路由使用解讀
今天總結(jié)下Vue3中路由相關(guān)的知識(shí),大致分為以下4點(diǎn):路由的理解,路由的引入與創(chuàng)建,非編程式路由導(dǎo)航,編程式路由導(dǎo)航。
1.路由的理解
單頁面應(yīng)用中,通過各種方式(點(diǎn)擊或自動(dòng)或條件跳轉(zhuǎn)等等操作)使展示區(qū)中呈現(xiàn)路由組件。
各種方式
- 非編程式路由導(dǎo)航
- 編程式路由導(dǎo)航
展示區(qū)
寫法為<routerView/>,vue-router提供的組件,使用時(shí)不需要引入,用于固定需要展示路由組件的位置。
路由組件和普通組件的區(qū)別
可以和普通組件做區(qū)分,路由組件和普通組件的區(qū)別:
- 普通組件一般需要手動(dòng)寫在某組件的<templete>標(biāo)簽體中,而路由組件是寫在管理路由規(guī)則的文件中,通俗易懂的來說,普通組件寫在html中,而路由組件寫在js或ts中;
- 根據(jù)Vue3工程化寫法的規(guī)則,普通組件存在于components命名的文件夾中,而路由組件存在于pages或views命名的文件夾中。
普通組件 Header:
// src/App.vue
<script setup lang="ts">
import Header from './components/Header.vue';
</script>
<template>
<Header/>
</template>
<style scoped>
</style>
路由組件 Home:
// src/router/index.ts
import Home from '@/pages/Home.vue'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
name: 'shouye',
path: '/home',
component: Home
},
})
export default router2.路由的引入和創(chuàng)建
引入
npm i vue-router
創(chuàng)建
創(chuàng)建router文件夾,創(chuàng)建index.ts文件,這里是工程化創(chuàng)建方式,不一定非要這樣命名。

從vue-router中引入創(chuàng)建路由的api,稱createRouter;引入要?jiǎng)?chuàng)建路由的模式,一個(gè)歷史模式,一個(gè)哈希模式。
// src/router/index.ts
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router"createWebHistory(History模式) 與 createWebHashHistory(Hash模式)的優(yōu)缺點(diǎn):
| createWebHistory(History模式) | createWebHashHistory(Hash模式) |
|---|---|
| 路徑中沒有#,很美觀 | 路徑中有#,不美觀 |
| 需要后端配合處理 | 不需要后端處理 |
| 常用在購物網(wǎng),產(chǎn)品介紹網(wǎng)站 | 常用在公司后臺(tái)管理系統(tǒng) |
引入路由組件(創(chuàng)建組件這里省略過程,跟普通組件一樣,注意創(chuàng)建的位置就行)
// src/router/index.ts
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router"
import Home from '@/pages/Home.vue'
import About from '@/pages/About.vue'
import News from '@/pages/News.vue'
import Details from '@/pages/Details.vue'創(chuàng)建路由規(guī)則,選擇模式,不要忘記最后要把router暴露出去。
// src/router/index.ts
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router"
import Home from '@/pages/Home.vue'
import About from '@/pages/About.vue'
import News from '@/pages/News.vue'
import Details from '@/pages/Details.vue'
const router = createRouter({
history: createWebHashHistory(),
// createWebHistory:History模式
// createWebHashHistory:Hash模式
routes: [
{
name: 'shouye',
path: '/home,
component: Home,
},
{
name: 'guanyu',
path: '/about',
component: About,
},
{
name: 'xinwen',
path: '/news',
component: News,
children: [
{
name: 'xiangqing',
path: 'details',
component: Details
}
]
}
]
})
export default router在入口文件main.ts中引入剛才創(chuàng)建好的路由規(guī)則,并且讓vue使用它。這樣我們的路由就已經(jīng)創(chuàng)建好并使用規(guī)則了。
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from "@/router"; // 引入剛才創(chuàng)建的路由規(guī)則
const app = createApp(App)
app.use(router) // 一定要在掛載之前使用這個(gè)規(guī)則
app.mount('#app')
3. 非編程式路由導(dǎo)航
上方已經(jīng)創(chuàng)建好了路由規(guī)則,我們該在路由組件中去創(chuàng)建路由導(dǎo)航區(qū)和路由展示區(qū)了。
使用場景
點(diǎn)擊路由導(dǎo)航區(qū)來切換展示區(qū)中的路由組件。
路由導(dǎo)航區(qū)
vue-router提供類似于a標(biāo)簽的組件<routerLink/>,標(biāo)簽體中可以寫屬性(push / replace)來決定跳轉(zhuǎn)方法,默認(rèn)為push方法。
replace 屬性替換當(dāng)前路由,沒有不可回退;而push添加新的歷史記錄,支持回退。
// src/App.ts <script setup lang="ts"> </script> <template> <router-link to="/home" replace>首頁</router-link> | <router-link to="/about" push>關(guān)于</router-link>| <router-link to="/news" push>新聞</router-link> <router-view/> </template> <style scoped> </style>
標(biāo)簽屬性
to屬性(重點(diǎn))
通過to屬性可以指定目標(biāo)路由,to屬性支持6種傳參方式,如下:
// const userId = ref('aaaaa')
// const userName= ref('bbbbbb')
// 1.to的字符串寫法傳遞query參數(shù)
<router-link to="/detail/?userId=${userId}&userName=${userName}">詳情</router-link>
// 2.to的字符串寫法傳遞param參數(shù)
<router-link to="/detail/${userId}/${userName}">詳情</router-link>
// 3.to的對象寫法通過path方式傳遞query參數(shù)
<router-link :to="{path: '/detail', query: {userId, userName}">詳情</router-link>
// 4.to的對象寫法通過path方式傳遞params參數(shù)
<router-link :to="{path: '/detail', params: {userId, userName}">詳情</router-link>
// 5.to的對象寫法通過name方式傳遞query參數(shù)
<router-link :to="{name: 'xiangqing', query: {userId, userName}">詳情</router-link>
// 6.to的對象寫法通過name方式傳遞params參數(shù)
<router-link :to="{name: 'xiangqing', params: {userId, userName}">詳情</router-link>
不同傳參類型的路由規(guī)則配置
to傳遞不同類型的參數(shù)(query或params),會(huì)影響路由規(guī)則中path屬性的寫法。
// src/router/index.ts
import { createRouter, createWebHashHistory } from "vue-router"
import News from '@/pages/News.vue'
import Detail from '@/pages/Detail.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{
name: 'xinwen',
path: '/news',
component: News,
// 注意:子組件path開頭不加斜杠
children: [
{
name: 'xiangqing',
path: 'detail', // 1.傳遞query參數(shù)時(shí),不用寫占位符
component: Detail,
}
{
name: 'xiangqing',
path: 'detail/:userId/:userName' // 2.傳遞param參數(shù)時(shí),path必須用占位符
component: Detail,
}
]
}
]
})
export default router接收參數(shù)
子組件接收參數(shù)的方式也多種多樣,這里距離兩種常見的收參方式:
這里不展示同時(shí)傳遞兩種類型參數(shù)的寫法了,我選其中一種來進(jìn)行演示。有興趣的朋友可以自行研究一下,是可以同時(shí)傳遞的。
普通收參:子組件中拿到路由對象后需要手動(dòng)解構(gòu)出參數(shù),對應(yīng)的路由規(guī)則中不需要做任何額外變動(dòng)。
// src/pages/detail.vue
<template>
<div>我是{{ query.userId}}-{{ query.userName}}</div> // 或者
<div>我是{{ params.userId}}-{{ params.userName}}</div>
</template>
<script setup lang="ts">
import { toRefs } from "vue";
import { useRoute } from "vue-router"; // 拿到路由
const route = useRoute()
// 響應(yīng)式的數(shù)據(jù)解構(gòu)出來的屬性并不會(huì)是響應(yīng)式的,需要toRefs手動(dòng)響應(yīng)式
const { query, params } = toRefs(route)
</script>
<style scoped>
</style>
// src/router/index.ts 不需要添加其他額外屬性
children: [
{
name: 'xiangqing',
path: 'detail',
component: Detail,
}
]簡便收參:子組件直接通過defineProps把參數(shù)定義出來就可以使用了,但對應(yīng)的路由規(guī)則需要添加props屬性,props有兩種寫法。
// src/pages/detail.vue
<template>
<div>我是{{ userId }}-{{ userName }}</div> // 兩種參數(shù)類型都可以直接用
</template>
<script setup lang="ts">
defineProps(['userId ','userName ']) // 定義出參數(shù)就可以用了
</script>
<style scoped>
</style>// src/router/index.ts 對應(yīng)的子組件路由規(guī)則
// 1.布爾類型props
.....略.....
children: [
{
name: 'xiangqing',
path: 'detail',
component: Detail,
props: true // 布爾寫法只能處理params參數(shù)
}
]
// 2.函數(shù)類型props
children: [
{
name: 'xiangqing',
path: 'detail',
component: Detail,
props(to) { // 函數(shù)寫法既可以處理query參數(shù),又可以處理params參數(shù)。
return {
query: to.query,
params: to.params
}
},
}
]
.....略.....4. 編程式路由導(dǎo)航
理解
已經(jīng)到這里了,沒有仔細(xì)看前面非編程式路由導(dǎo)航的朋友一定要回去瞅瞅,你會(huì)發(fā)現(xiàn)你對編程式路由導(dǎo)航的學(xué)習(xí)成本為0,不信?請您繼續(xù)看。
vue-router提供了一個(gè)API,叫useRouter,使用其實(shí)例中的跳轉(zhuǎn)方法(push / replace)來切換展示區(qū)中的路由組件。
使用場景
需要根據(jù)條件切換路由組件。
寫法示例
需求:點(diǎn)擊不同的按鈕,不同秒數(shù)后攜帶不同的參數(shù)進(jìn)行不同方式路由跳轉(zhuǎn)。
// src/pages/detail.vue
<template>
<div>詳情組件</div>
<button @click="jump(3000, true)">點(diǎn)擊我3秒后使用默認(rèn)模式push進(jìn)入詳情1</button>
<button @click="jump(5000, false)">點(diǎn)擊我5秒后使用replace模式進(jìn)入詳情2</button>
<router-view/>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
const router = useRouter() // 引入路由器
let timer = null
function jump(delay: number, jumpType: boolean) {
timer = setTimeout(() => {
if(jumpType){
router.push({ // 默認(rèn)為push模式,可回退記錄
name: 'xiangqing',
params: {
id: '11',
content: '1111'
},
})
}else{
router.replace({ // replace模式,不可回退。
name: 'xiangqing',
params: {
id: 'params1',
content: 'params2'
},
query: {
id: 'query3',
content: 'query4'
},
})
}
}, delay)
}
</script>
<style scoped>
</style>
發(fā)現(xiàn)沒有朋友們,router.push(obj), 這個(gè)obj的寫法,和前面的非編程式路由導(dǎo)航中的to寫法一摸一樣,沒看懂的朋友可以看看前面對非編程式導(dǎo)航對to屬性的詳解。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue在.js文件中如何進(jìn)行路由跳轉(zhuǎn)
這篇文章主要介紹了vue在.js文件中如何進(jìn)行路由跳轉(zhuǎn),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
webpack+vue中使用別名路徑引用靜態(tài)圖片地址
這篇文章主要介紹了webpack+vue中使用別名路徑引用靜態(tài)圖片地址,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
Vue3使用transition組件改變DOM屬性的方式小結(jié)
這篇文章主要為大家詳細(xì)介紹了Vue3中使用transition組件改變DOM屬性的常用方式,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01
Vue.js實(shí)現(xiàn)可配置的登錄表單代碼詳解
這篇文章主要介紹了Vue.js實(shí)現(xiàn)可配置的登錄表單實(shí)例代碼詳解,文中給大家補(bǔ)充介紹了vue.js 全選與取消全選的實(shí)例代碼,需要的朋友可以參考下2018-03-03
Vue-cli創(chuàng)建項(xiàng)目從單頁面到多頁面的方法
本篇文章主要介紹了Vue-cli創(chuàng)建項(xiàng)目從單頁面到多頁面的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
Vue關(guān)于數(shù)據(jù)綁定出錯(cuò)解決辦法
這篇文章主要介紹了Vue關(guān)于數(shù)據(jù)綁定出錯(cuò)解決辦法的相關(guān)資料,需要的朋友可以參考下2017-05-05
vue使用stompjs實(shí)現(xiàn)mqtt消息推送通知
這篇文章主要為大家詳細(xì)介紹了vue中使用stompjs實(shí)現(xiàn)mqtt消息推送通知,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

