解決vue路由name同名,路由重復的問題
在項目中,想讓路由后綴為空,或者index的時候,都跳轉(zhuǎn)到路由為index的頁面,于是在router中如下配置
routes: [{ path: '/', name: 'index', component: () => import('@/components/index').then(m => m.default) },{ path: '/index', name: 'index', component: () => import('@/components/index').then(m => m.default) }]
但是瀏覽器告警信息:
[vue-router] Duplicate named routes definition: { name: "index", path: "/index" }
因為路由重復添加,name一樣造成,利用redirect重定向
routes: [{ path: '/', redirect: { name: index } // name: 'index', // component: () => import('@/components/index').then(m => m.default) },{ path: '/index', name: 'index', component: () => import('@/components/index').then(m => m.default) }]
補充知識:vue路由使用踩坑點:當動態(tài)路由再使用路由name去匹配跳轉(zhuǎn)時總是跳轉(zhuǎn)到根路由的問題
閑話少說,直接問題:
之前我的路由時這么寫的
{ path:'/serverInfo/:id', name:'serverInfo', component:() => import('@/views/serverRequest/SRInfo') }
但是呢,頭部做了個通知面板,代碼如下:
<el-popover popper-class="messagePopper" placement="bottom" width="300" v-model="visiblity" trigger="click"> <div class="messageBox"> <div class="title">通知</div> <div class="message" v-if="messageData.length === 0">暫無通知</div> <div v-else> <div class="message" v-for="item in messageData" @click="readMessage(item.id)"> <router-link :to="{ name:item.route, params:{ messageId:item.rid } }">{{'【' + item.message + '】'}}</router-link> <span>{{item.message_time}}</span> </div> </div> </div> <el-badge slot="reference" :value="messageData.length" class="item" :hidden="messageData.length === 0"> <i class="messageStyle iconfont icon-tongzhi"></i> <span class="messageText">通知</span> </el-badge> </el-popover>
看一下router-link部分通過name去跳轉(zhuǎn),并傳遞參數(shù)。
然后我們可以看一下頁面,order路由正常的,serverInfo就不正常了
我們看下后臺返回數(shù)據(jù)也是正常的有路由名字,這就很惆悵了。
然后我們看下order的路由,order沒有動態(tài)路由匹配。
{ path:'/order', name:'order', component:() => import('@/views/system/order') },
所以初步猜測:是不是有動態(tài)路由匹配時,通過路由name去跳轉(zhuǎn),就會匹配不到全路徑,而跑到根路由去呢?
我們現(xiàn)在把serverInfo路由改一下:去掉動態(tài)路由匹配
{ path:'/serverInfo', name:'serverInfo', component:() => import('@/views/serverRequest/SRInfo') }
改了之后,我們之前使用到的路由跳轉(zhuǎn)的地方也得改下。我們需要傳參數(shù)的地方就通過下面這種去傳,也是一樣的
// <router-link :to="'/serverInfo/'+scope.row.srid"> <router-link :to="{name:'serverInfo',params:{id:scope.row.srid}}"> <span>{{scope.row.srid}}</span> </router-link>
改成這樣只會就發(fā)現(xiàn)一切正常了
所以總結(jié)一下:
當使用動態(tài)路由匹配的時候,再想通過name去跳轉(zhuǎn)是會有問題的。當你想用路由name去跳轉(zhuǎn)的時候,就不要使用動態(tài)路由匹配,需要傳參數(shù),就使用params去傳遞參數(shù)。
以上這篇解決vue路由name同名,路由重復的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue使用 onMounted 確保在組件掛載后執(zhí)行異步操作示例詳解
在 Vue.js 或其他類似框架中,使用 onMounted 是為了確保在組件掛載后執(zhí)行異步操作,這篇文章主要介紹了Vue使用onMounted確保在組件掛載后執(zhí)行異步操作,需要的朋友可以參考下2023-06-06Vue+elementUI實現(xiàn)動態(tài)展示列表的數(shù)據(jù)
這篇文章主要介紹了Vue+elementUI實現(xiàn)動態(tài)展示列表的數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08