vue-router路由配置實(shí)踐
路由配置主要是用來確定網(wǎng)站訪問路徑對應(yīng)哪個(gè)文件代碼顯示的,這里主要描述路由的配置、子路由、動態(tài)路由(運(yùn)行中添加刪除路由)
1、npm添加
npm install vue-router // 執(zhí)行完后會自動在package.json中添加 "vue-router": "^4.0.15" // 如果區(qū)分dev或發(fā)布版本中使用,把上面添加的拷貝過去即可
2、在main.js中添加使用
(主要是下面第3/13行)
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import router from '../router'
import 'element-plus/dist/index.css'
import './index.css' // 這個(gè)居中對齊了,不知道有哪些功能
import App from './App.vue'
const app = createApp(App)
// app.use(ElementPlus)
// app.mount('#app')
app
.use(ElementPlus)
.use(router)
.mount('#app')3、上面import的router需要在根目錄下
創(chuàng)建router文件夾,里面添加index.js文件
import {createRouter, createWebHashHistory} from "vue-router";
// import Home from "../views/test.vue";
const routes = [
{
path: '*', // 默認(rèn)在Home頁面,沒有匹配到路由時(shí)使用
redirect: '/Home'
}, {
path: '/',
redirect: '/test'
}, {
path: '/test',
name: 'test',
// 上面importvue文件名后在''中添加名字即可,或按需引入
component: () => import('../views/test.vue')
}
]
const router = createRouter({
// createWebHashHistory路徑有#號,createWebHistory路徑不包含#。使用web方式部署到服務(wù)器刷新會報(bào)404錯(cuò)誤
history: createWebHashHistory(),
routes
});
// router.beforeEach((to, from, next) => {
// document.title = `${to.meta.title} | vue-manage-system`;
// const role = localStorage.getItem('ms_username');
// if (!role && to.path !== '/login') {
// next('/login');
// } else if (to.meta.permission) {
// // 如果是管理員權(quán)限則可進(jìn)入,這里只是簡單的模擬管理員權(quán)限而已
// role === 'admin'
// ? next()
// : next('/403');
// } else {
// next();
// }
// });
export default router4、在App.vue中添加顯示
// router-view顯示內(nèi)容
<template>
<div id="app" >
<router-view/>
</div>
</template>5、router-link路由鏈接
跳轉(zhuǎn)到指定位置
<!-- 字符串 -->
<router-link to="/home">Home</router-link>
<!-- 渲染結(jié)果 -->
<a href="/home" rel="external nofollow" >Home</a>
<!-- 使用 v-bind 的 JS 表達(dá)式 -->
<router-link :to="'/home'">Home</router-link>
<!-- 同上 -->
<router-link :to="{ path: '/home' }">Home</router-link>
<!-- 命名的路由 -->
<router-link :to="{ name: 'user', params: { userId: '123' }}">User</router-link>
<!-- 帶查詢參數(shù),下面的結(jié)果為 `/register?plan=private` -->
<router-link :to="{ path: '/register', query: { plan: 'private' }}">
Register
</router-link>6、如何根據(jù)router切換子窗體
嵌套路由,示例代碼:

路由下加變量訪問
const User = {
template: '<div>User {{ $route.params.id }}</div>',
}
// 這些都會傳遞給 `createRouter`
const routes = [{ path: '/user/:id', component: User }]子路由(router-view顯示的內(nèi)容中還有router-view),如下需要配置默認(rèn)打開的子路由及顯示對應(yīng)子路由
const routes = [
{
path: '/user/:id',
component: User,
children: [
// 當(dāng) /user/:id 匹配成功
// UserHome 將被渲染到 User 的 <router-view> 內(nèi)部
{ path: '', component: UserHome },
// ...其他子路由
{
// 當(dāng) /user/:id/profile 匹配成功
// UserProfile 將被渲染到 User 的 <router-view> 內(nèi)部
path: 'profile',
component: UserProfile,
},
{
// 當(dāng) /user/:id/posts 匹配成功
// UserPosts 將被渲染到 User 的 <router-view> 內(nèi)部
path: 'posts',
component: UserPosts,
},
],
},
]7、同級目錄下有多個(gè)顯示
<ul>
<li>
<router-link to="/">First page</router-link>
</li>
<li>
<router-link to="/other">Second page</router-link>
</li>
</ul>
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>路由配置如下
import { createRouter, createWebHistory } from 'vue-router'
import First from './views/First.vue'
import Second from './views/Second.vue'
import Third from './views/Third.vue'
export const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
// a single route can define multiple named components
// which will be rendered into <router-view>s with corresponding names.
components: {
default: First,
a: Second,
b: Third,
},
},
{
path: '/other',
components: {
default: Third,
a: Second,
b: First,
},
},
],
})
不用路由,vue加載顯示
<template>
<div>
<Header/>
</div>
</template>
<script>
import { useRouter } from "vue-router";
import Header from "../src/components/Header.vue";
import vTags from "../src/components/Tags.vue";
export default {
components: {
Header,
vTags,
},
}
</script>嵌套路由時(shí)
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
import { useRouter } from "vue-router";
export default {
methods:{
clickMenu(item) {
console.log(item);
// console.log(item.name);
this.$router.push({
item
// name: 'About'
})
}
},
</script>別人的教程代碼,主要是看注釋
import { createRouter } from'@naturefw/ui-elp'
import home from'../views/home.vue'
const router = {
/** * 基礎(chǔ)路徑 */
baseUrl: baseUrl,
/** * 首頁 */
home: home,
menus: [
{
menuId: '1', // 相當(dāng)于路由的 name
title: '全局狀態(tài)', // 瀏覽器的標(biāo)題
naviId: '0', // 導(dǎo)航ID
path: 'global', // 相當(dāng)于 路由 的path
icon: FolderOpened, // 菜單里的圖標(biāo)
childrens: [ // 子菜單,不是子路由。
{
menuId: '1010', // 相當(dāng)于路由的 name
title: '純state',
path: 'state',
icon: Document,
// 加載的組件
component: () =>import('../views/state-global/10-state.vue')
// 還可以有子菜單。
},
{
menuId: '1020',
title: '一般的狀態(tài)',
path: 'standard',
icon: Document,
component: () =>import('../views/state-global/20-standard.vue')
}
]
},
{
menuId: '2000',
title: '局部狀態(tài)',
naviId: '0',
path: 'loacl',
icon: FolderOpened,
childrens: [
{
menuId: '2010',
title: '父子組件',
path: 'parent-son',
icon: Document,
component: () =>import('../views/state-loacl/10-parent.vue')
}
]
}
]
}
exportdefault createRouter(router )8、push、replace函數(shù)
router.push(location)
使用 router.push 方法。這個(gè)方法會向 history 棧添加一個(gè)新記錄,當(dāng)用戶點(diǎn)擊瀏覽器后退按鈕時(shí),可以返回到之前的URL,所以,等同于
router.replace()導(dǎo)航后不會留下 history 記錄。點(diǎn)擊返回按鈕時(shí),不會返回到這個(gè)頁面。
9、動態(tài)路由
動態(tài)路由主要通過兩個(gè)函數(shù)實(shí)現(xiàn)。router.addRoute() 和 router.removeRoute()。
它們只注冊一個(gè)新的路由,也就是說,如果新增加的路由與當(dāng)前位置相匹配,就需要你用 router.push() 或 router.replace() 來手動導(dǎo)航,才能顯示該新路由。
之前在router文件夾下定義了router
const router = createRouter({
// createWebHashHistory路徑有#號,createWebHistory路徑不包含#并且無法刷新顯示(需要nginx適配)
history: createWebHashHistory(),
routes
});添加路由,并手動調(diào)用 router.replace() 來改變當(dāng)前的位置(覆蓋我們原來的位置)
router.addRoute({ path: '/about', component: About })
// 我們也可以使用 this.$route 或 route = useRoute() (在 setup 中)
router.replace(router.currentRoute.value.fullPath)如果你決定在導(dǎo)航守衛(wèi)內(nèi)部添加或刪除路由,你不應(yīng)該調(diào)用router.replace(),而是通過返回新的位置來觸發(fā)重定向:
router.beforeEach(to => {
if (!hasNecessaryRoute(to)) {
router.addRoute(generateRoute(to))
// 觸發(fā)重定向
return to.fullPath
}
})通過添加一個(gè)名稱沖突的路由。如果添加與現(xiàn)有途徑名稱相同的途徑,會先刪除路由,再添加路由(以下三種刪除方式):
// 這將會刪除之前已經(jīng)添加的路由,因?yàn)樗麄兙哂邢嗤拿智颐直仨毷俏ㄒ坏?
const removeRoute = router.addRoute(routeRecord)
// 刪除路由如果存在的話
removeRoute()
// 刪除路由
router.removeRoute('about')
// 添加路由
router.addRoute({ path: '/other', name: 'about', component: Other })添加嵌套路由
router.addRoute({ name: 'admin', path: '/admin', component: Admin })
router.addRoute('admin', { path: 'settings', component: AdminSettings })
// 上面等效于如下實(shí)現(xiàn)方式
router.addRoute({
name: 'admin',
path: '/admin',
component: Admin,
children: [{ path: 'settings', component: AdminSettings }],
})查看現(xiàn)有路由
Vue Router 提供了兩個(gè)功能來查看現(xiàn)有的路由:
- router.hasRoute():檢查路由是否存在。
- router.getRoutes():獲取一個(gè)包含所有路由記錄的數(shù)組。
10、動態(tài)路由用于登錄
// 在login界面的事件中校驗(yàn)完成后,把用戶名和密碼存到本地,使用localStorage.getItem讀取
localStorage.setItem("ms_username", param.username);
// 登錄成功后觸發(fā)訪問其他頁面
router.push("/");在router中添加如下處理。beforeEach:添加一個(gè)導(dǎo)航守衛(wèi),在任何導(dǎo)航前執(zhí)行。返回一個(gè)刪除已注冊守衛(wèi)的函數(shù)
router.beforeEach((to, from, next) => {
document.title = `${to.meta.title} | vue-manage-system`;
const role = localStorage.getItem('ms_username');
if (!role && to.path !== '/login') {
next('/login');
} else if (to.meta.permission) {
// 如果是管理員權(quán)限則可進(jìn)入,這里只是簡單的模擬管理員權(quán)限而已
role === 'admin'
? next()
: next('/403');
} else {
next();
}
});總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue+spring boot實(shí)現(xiàn)校驗(yàn)碼功能
這篇文章主要為大家詳細(xì)介紹了vue+spring boot實(shí)現(xiàn)校驗(yàn)碼功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05
vue隨機(jī)驗(yàn)證碼組件的封裝實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了如何封裝一個(gè)隨機(jī)驗(yàn)證碼的VUE組件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02
Vue+Element實(shí)現(xiàn)頁面生成快照截圖
這篇文章主要為大家詳細(xì)介紹了Vue如何結(jié)合Element實(shí)現(xiàn)頁面生成快照截圖功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03
vue頁面設(shè)置滾動失敗的完美解決方案(scrollTop一直為0)
這篇文章主要介紹了vue頁面設(shè)置滾動失敗的解決方案(scrollTop一直為0),本文通過場景分析實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
el-date-picker 選擇日期范圍只保存左側(cè)日期面板的實(shí)現(xiàn)代碼
接到這樣的需求,日期篩選,但限制只能選擇同一個(gè)月的數(shù)據(jù),故此應(yīng)該去掉右側(cè)月份面板,今天通過本文給大家分享el-date-picker 選擇日期范圍只保存左側(cè)日期面板的實(shí)現(xiàn)代碼,感興趣的朋友一起看看吧2024-06-06
Babel自動生成Attribute文檔實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了Babel自動生成Attribute文檔實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
uni-app中App與webview雙向?qū)崟r(shí)通信詳細(xì)代碼示例
在移動應(yīng)用開發(fā)中,uni-app是一個(gè)非常流行的框架,它允許開發(fā)者使用一套代碼庫構(gòu)建多端應(yīng)用,包括H5、小程序、App等,這篇文章主要給大家介紹了關(guān)于uni-app中App與webview雙向?qū)崟r(shí)通信的相關(guān)資料,需要的朋友可以參考下2024-07-07
Vue實(shí)現(xiàn)動態(tài)樣式的多種方法匯總
本文要給大家介紹Vue實(shí)現(xiàn)動態(tài)樣式的多種方法,下面給大家?guī)韼讉€(gè)案列,需要的朋友可以借鑒研究一下。2021-06-06

