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模式了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容