vue3中,配合的vueRouter版本更改為vue-router-next
通過
npm i vue-router@next
的方式進行引入添加鸳谜,隨后創(chuàng)建 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對應(yīng)的vueRouter版本通過mode:'hash',mode:'history',mode:'abstract'方式有所不同,在現(xiàn)階段的網(wǎng)上的教程,沒有說明vue3的hash模式如何開啟,默認都是history模式
因此通過 localhost:8080/#/hello 或者
localhost:8080/#/cards 無法進入到對應(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 這三個正是我們想要的;
createWebHistory: 對應(yīng) mode:'history'
createWebHashHistory : 對應(yīng)mnode:'hash'
createMemoryHistory: 這個是在內(nèi)存中進行匹配, 對應(yīng)的應(yīng)該是 'abstract',
因此,將路由定義時候
const history = createWebHistory();
更改為
const history = createWebHashHistory();
就能達到原來vue2中對應(yīng)的hash模式了