vue-router-next 通過hash模式訪問頁面不生效,直接刷新頁面一直停留在根路由界面的解決辦法

vue3中,配合的vueRouter版本更改為vue-router-next

通過

npm i vue-router@next

的方式進(jìn)行引入添加,隨后創(chuàng)建 router.js,在main.js里面引入, 通過app.use(router)的方式進(jìn)行使用;

import {createRouter, createWebHistory} from 'vue-router';

const history = createWebHistory();

const router = createRouter({

history,

routes: [

? {

? ? path: '/',

? ? name: 'Home',

? ? component: () => import('./views/Home/index.vue'),

? },

? {

? ? path: '/cards',

? ? name: 'Cards',

? ? component: () => import('./views/Cards/index.vue'),

? },

? {

? ? path: '/hello',

? ? name: 'Hello',

? ? component: () => import('./components/HelloWorld.vue'),

? },

?],

});

export default router;

這個(gè)模式

const history = createWebHistory();

和之前vue2對應(yīng)的vueRouter版本通過mode:'hash',mode:'history',mode:'abstract'方式有所不同,在現(xiàn)階段的網(wǎng)上的教程,沒有說明vue3的hash模式如何開啟,默認(rèn)都是history模式

因此通過 localhost:8080/#/hello 或者

localhost:8080/#/cards 無法進(jìn)入到對應(yīng)的路由頁面;

通過查看打印 vue-router-next 對外暴露的方法, 找到了vue-router-next版本下開啟 hash模式的方法

import * as res from 'vue-router'; // 引入vueRouter所有暴露的方法并取別名 res

console.log(Object.keys(res)); // 將res所有屬性的key值轉(zhuǎn)成數(shù)組并打印

// ['NavigationFailureType', 'RouterLink', 'RouterView', 'START_LOCATION', 'createMemoryHistory', 'createRouter', 'createRouterMatcher', 'createWebHashHistory', 'createWebHistory', 'isNavigationFailure', 'onBeforeRouteLeave', 'onBeforeRouteUpdate', 'parseQuery', 'stringifyQuery', 'useLink', 'useRoute', 'useRouter'];

找到上面createWebHistory 相類似的API: createWebHistory? createMemoryHistory? createWebHashHistory 這三個(gè)正是我們想要的;

createWebHistory: 對應(yīng) mode:'history'

createWebHashHistory : 對應(yīng)mnode:'hash'

createMemoryHistory: 這個(gè)是在內(nèi)存中進(jìn)行匹配, 對應(yīng)的應(yīng)該是 'abstract',

因此,將路由定義時(shí)候

const history = createWebHistory();

更改為

const history = createWebHashHistory();

就能達(dá)到原來vue2中對應(yīng)的hash模式了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容