1. 安裝 Vue Router 4
npm install vue-router@4
# 或
yarn add vue-router@4
2. 創(chuàng)建路由配置文件
在src目錄下創(chuàng)建router文件夾,并在其中創(chuàng)建index.js文件:
import { createRouter, createWebHistory } from 'vue-router'
// 導(dǎo)入需要的組件
import NormalHomePage from '@/pages/NormalHomePage.vue'
import About from '@/pages/About.vue'
import FundRankList from '@/pages/FundRankList.vue'
// 定義路由規(guī)則
const routes = [
{
// 這是默認(rèn)路徑
path: '/',
name: 'NormalHomePage',
component: NormalHomePage
},
{
path: '/about',
name: 'About',
component: About
},
{
path: '/fund-rank-list',
name: 'FundRankList',
component: FundRankList,
props: true // 允許通過路由傳遞props
}
]
// 創(chuàng)建路由實(shí)例
const router = createRouter({
// 選擇路由模式:hash 或 history
// createWebHashHistory() // 使用 hash 模式 (帶 # 號(hào))
history: createWebHistory(process.env.BASE_URL), // 使用 history 模式 (需要后端支持)
routes
})
// 全局路由守衛(wèi)(可選)
router.beforeEach((to, from, next) => {
// 可以在這里添加權(quán)限驗(yàn)證等邏輯
console.log('即將跳轉(zhuǎn)到:', to.name)
next()
})
export default router
3. 在main.js中配置路由
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
// 導(dǎo)入路由配置
import router from './router'
// 1. 先創(chuàng)建Pinia實(shí)例
const pinia = createPinia()
const app = createApp(App)
// 2. 先使用Pinia
app.use(pinia)
// 3. 使用路由
app.use(router)
// 掛載應(yīng)用
app.mount('#app')
4. 在App.vue中添加路由視圖
<template>
<div id="app">
<!-- 路由出口:渲染當(dāng)前路由對應(yīng)的組件 -->
<router-view />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
5. 在組件中使用路由
在組件中跳轉(zhuǎn)路由
import { useRouter } from 'vue-router'
export default {
setup() {
const router = useRouter()
// 跳轉(zhuǎn)到指定路由
const navigateToAbout = () => {
router.push('/about')
}
// 帶參數(shù)跳轉(zhuǎn)
const goToFundRank = (id) => {
router.push({
name: 'FundRankList',
params: { id }
})
}
return {
navigateToAbout,
goToFundRank
}
}
}
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
// 獲取路由參數(shù)
const fundId = route.params.id
return {
fundId
}
}
}