vue-router路由配置實(shí)踐
路由配置主要是用來(lái)確定網(wǎng)站訪問(wèn)路徑對(duì)應(yīng)哪個(gè)文件代碼顯示的,這里主要描述路由的配置、子路由、動(dòng)態(tài)路由(運(yùn)行中添加刪除路由)
1、npm添加
npm install vue-router // 執(zhí)行完后會(huì)自動(dòng)在package.json中添加 "vue-router": "^4.0.15" // 如果區(qū)分dev或發(fā)布版本中使用,把上面添加的拷貝過(guò)去即可
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è)居中對(duì)齊了,不知道有哪些功能
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頁(yè)面,沒(méi)有匹配到路由時(shí)使用
redirect: '/Home'
}, {
path: '/',
redirect: '/test'
}, {
path: '/test',
name: 'test',
// 上面importvue文件名后在''中添加名字即可,或按需引入
component: () => import('../views/test.vue')
}
]
const router = createRouter({
// createWebHashHistory路徑有#號(hào),createWebHistory路徑不包含#。使用web方式部署到服務(wù)器刷新會(huì)報(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)入,這里只是簡(jiǎ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切換子窗體
嵌套路由,示例代碼:

路由下加變量訪問(wèn)
const User = {
template: '<div>User {{ $route.params.id }}</div>',
}
// 這些都會(huì)傳遞給 `createRouter`
const routes = [{ path: '/user/:id', component: User }]子路由(router-view顯示的內(nèi)容中還有router-view),如下需要配置默認(rèn)打開(kāi)的子路由及顯示對(duì)應(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、同級(jí)目錄下有多個(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,
/** * 首頁(yè) */
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è)方法會(huì)向 history 棧添加一個(gè)新記錄,當(dāng)用戶點(diǎn)擊瀏覽器后退按鈕時(shí),可以返回到之前的URL,所以,等同于
router.replace()導(dǎo)航后不會(huì)留下 history 記錄。點(diǎn)擊返回按鈕時(shí),不會(huì)返回到這個(gè)頁(yè)面。
9、動(dòng)態(tài)路由
動(dòng)態(tài)路由主要通過(guò)兩個(gè)函數(shù)實(shí)現(xiàn)。router.addRoute() 和 router.removeRoute()。
它們只注冊(cè)一個(gè)新的路由,也就是說(shuō),如果新增加的路由與當(dāng)前位置相匹配,就需要你用 router.push() 或 router.replace() 來(lái)手動(dòng)導(dǎo)航,才能顯示該新路由。
之前在router文件夾下定義了router
const router = createRouter({
// createWebHashHistory路徑有#號(hào),createWebHistory路徑不包含#并且無(wú)法刷新顯示(需要nginx適配)
history: createWebHashHistory(),
routes
});添加路由,并手動(dòng)調(diào)用 router.replace() 來(lái)改變當(dāng)前的位置(覆蓋我們?cè)瓉?lái)的位置)
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(),而是通過(guò)返回新的位置來(lái)觸發(fā)重定向:
router.beforeEach(to => {
if (!hasNecessaryRoute(to)) {
router.addRoute(generateRoute(to))
// 觸發(fā)重定向
return to.fullPath
}
})通過(guò)添加一個(gè)名稱沖突的路由。如果添加與現(xiàn)有途徑名稱相同的途徑,會(huì)先刪除路由,再添加路由(以下三種刪除方式):
// 這將會(huì)刪除之前已經(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è)功能來(lái)查看現(xiàn)有的路由:
- router.hasRoute():檢查路由是否存在。
- router.getRoutes():獲取一個(gè)包含所有路由記錄的數(shù)組。
10、動(dòng)態(tài)路由用于登錄
// 在login界面的事件中校驗(yàn)完成后,把用戶名和密碼存到本地,使用localStorage.getItem讀取
localStorage.setItem("ms_username", param.username);
// 登錄成功后觸發(fā)訪問(wèn)其他頁(yè)面
router.push("/");在router中添加如下處理。beforeEach:添加一個(gè)導(dǎo)航守衛(wèi),在任何導(dǎo)航前執(zhí)行。返回一個(gè)刪除已注冊(cè)守衛(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)入,這里只是簡(jiǎn)單的模擬管理員權(quán)限而已
role === 'admin'
? next()
: next('/403');
} else {
next();
}
});總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解基于iview-ui的導(dǎo)航欄路徑(面包屑)配置
這篇文章主要介紹了詳解基于iview-ui的導(dǎo)航欄路徑(面包屑)配置,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
vuepress項(xiàng)目側(cè)邊欄菜單配置使用方式
這篇文章主要介紹了vuepress項(xiàng)目側(cè)邊欄菜單配置使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-06-06
vxe-table?實(shí)現(xiàn)按回車鍵自動(dòng)新增一行(示例代碼)
本文通過(guò)示例代碼介紹了vxe-table新版本中實(shí)現(xiàn)回車自動(dòng)換行功能的方法,通過(guò)設(shè)置keyboard-config.isLastEnterAppendRow參數(shù)可以控制是否開(kāi)啟該功能,當(dāng)回車鍵在最后一行按下時(shí),會(huì)自動(dòng)新增一行,并將光標(biāo)移動(dòng)到新行,代碼簡(jiǎn)單易懂,感興趣的朋友跟隨小編一起看看吧2024-12-12

