1. 程式人生 > 實用技巧 >vue-router-next 通過hash模式訪問頁面不生效,直接重新整理頁面一直停留在根路由介面的解決辦法

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

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

  npm i vue-router@next

的方式進行引入新增,隨後建立 router.js,在main.js裡面引入, 通過app.use(router)的方式進行使用;

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;

這個模式
const history = createWebHistory();
和之前vue2對應的vueRouter版本通過mode:'hash',mode:'history',mode:'abstract'方式有所不同,在現階段的網上的教程,沒有說明vue3的hash模式如何開啟,預設都是history模式

因此通過 localhost:8080/#/hello 或者
localhost:8080/#/cards 無法進入到對應的路由頁面;

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

import * as res from 'vue-router'; // 引入vueRouter所有暴露的方法並取別名 res
console.log(Object.keys(res)); // 將res所有屬性的key值轉成陣列並列印

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

找到上面 createWebHistory 相類似的API:
createWebHistory createMemoryHistory createWebHashHistory 這三個正是我們想要的;
createWebHistory: 對應 mode:'history'
createWebHashHistory : 對應mnode:'hash'
createMemoryHistory: 這個是在記憶體中進行匹配, 對應的應該是 'abstract', 

因此,將路由定義時候
const history = createWebHistory();
更改為
const history = createWebHashHistory();
就能達到原來vue2中對應的hash模式了