Vue router 有沒有 hash 有差別
Vue 3 主要有 2 種處理路由的方式,分別是 Hash Mode 以及 HTML5 (History API) Mode 兩種。(其實還有一種 abstract 模式)
createWebHashHistory 模式
網址列多了一個 #
字號。
Hash 也就是 我們用來設定連結錨點的那個 #
字號。
<a hhref="https://xxx.com/#hashmark"></a>
利用改變#
後面對應到 HTML 檔案 id
的文字,就可以不用換頁,又可以在瀏覽器中留下「上一頁」與「下一頁」的歷史紀錄,而且切換時不會刷新頁面。
createWebHashHistory 模式預設的路徑為 location.pathname 或 / 根目錄,也可以改變預設路徑,使用 createWebHashHistory(‘/folder/‘),就可以對應到 https://xxxx.com/folder/# 。
Hash 模式完全是前端模式,只在瀏覽器中動作,不牽扯後端,缺點是對 SEO 不利,因為搜尋引擎會自動忽略 URL 有 #
的部分。
router.js
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue')
}
]
})
export default router
createWebHistory 模式
如果是 createWebHistory
就是採用 HTML5 的 History API,可以使用 pushState()
、replaceState()
等方法更新 URL,搭配原有的 history.go()、history.back()來指定頁面路徑切換,如,也提供了 state 物件讓開發這可以暫時存取網頁的狀態。
<a hhref="https://xxx.com/path"></a>
需要搭配後端路由,如果沒有後端的配置,使用者直接輸入網址,或瀏覽器重整網頁的時候會找不到網頁,跳 404 頁面。
router.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue')
}
]
})
export default router
Vue router 有沒有 hash 有差別
https://popeye-ux.github.io/2023/02/12/vue-router-historymode/