前言
vue路由的三種模式 Hash模式
、History模式
、abstract 模式
一、Hash模式
- Vue3:
- Hash 模式是用
createWebHashHistory()
創(chuàng)建的:
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
//...
],
})
- Vue2
import Router from 'vue-router'
const router = new Router({
node: 'hash',
routes: [
//...
]
})
它在內(nèi)部傳遞的實際 URL 之前使用了一個哈希字符(#)。由于這部分 URL 從未被發(fā)送到服務(wù)器,所以它不需要在服務(wù)器層面上進行任何特殊處理。不過,它在 SEO 中確實有不好的影響。如果你擔心這個問題,可以使用 HTML5 模式。
二、HTML5 (History)模式
- Vue3
- History模式是用
createWebHistory()
創(chuàng)建的:
import { createRouter, createWebHistory} from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
//...
],
})
- Vue2
import Router from 'vue-router'
const router = new Router({
node: 'history',
routes: [
//...
]
})
當使用這種歷史模式時,URL也會看起來很 “正?!保?https://example.com/user/id
history.go(-2);//后退兩次
history.go(2);//前進兩次
history.back(); //后退
hsitory.forward(); //前進
不過,問題來了。由于我們的應(yīng)用是一個單頁的客戶端應(yīng)用,如果沒有適當?shù)姆?wù)器配置,用戶在瀏覽器中直接訪問 https://example.com/user/id
,就會得到下圖 404 的錯誤。這就尷尬了。
Tips:本人參與的項目常見部署訪問基本是Nginx,偶爾有使用Internet Information Services (IIS)
- 解決方法如下:
1、nginx配置
修改nginx.conf文件如下:
location / {
try_files $uri $uri/ /index.html;
}
or
location / {
try_files $uri $uri/ @router;#需要指向下面的@router否則會出現(xiàn)vue的路由在nginx中刷新出現(xiàn)404
index index.html index.htm;
}
#對應(yīng)上面的@router,主要原因是路由的路徑資源并不是一個真實的路徑,所以無法找到具體的文件
#因此需要rewrite到index.html中,然后交給路由在處理請求資源
location @router {
rewrite ^.*$ /index.html last; # /index.html 為項目根目錄
}
2、Internet Information Services (IIS)配置
a、安裝 IIS UrlRewrite
b、在網(wǎng)站的根目錄下創(chuàng)建一個 web.config 文件,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and custom 404/500" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
三、Abstract 模式
abstract 是vue路由中的第三種模式,本身是用來在不支持瀏覽器API的環(huán)境中,暫未實際使用過,后期補充相關(guān)實現(xiàn)
- Vue3
- 在 SSR 上使用時,你需要手動傳遞相應(yīng)的 history:
- Abstract 模式是用
createMemoryHistory()
創(chuàng)建的:
// router.js
let history = isServer ? createMemoryHistory() : createWebHistory()
let router = createRouter({ routes, history })
// 在你的 server-entry.js 中的某個地方
router.push(req.url) // 請求 url
router.isReady().then(() => {
// 處理請求
})
總結(jié)
以上就是Vue不同的歷史模式內(nèi)容,本文簡單介紹了Vue History路由模式的使用,而具體的項目配置需根據(jù)項目實際情況配置。文章來源:http://www.zghlxwxcb.cn/news/detail-527579.html
感謝閱讀!
參考:Vue路由的不同的歷史模式文章來源地址http://www.zghlxwxcb.cn/news/detail-527579.html
到了這里,關(guān)于Vue路由模式(history模式 刷新頁面空白解決方案)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!