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模式了
原文地址:https://www.cnblogs.com/yifangts/p/13699622.html