說在前面的話:
Vue router有兩種模式,默認(rèn)的模式是hash,就是地址欄中有一個(gè)#來隔開域名和pathname。而這種方式一般在部署前后端分離項(xiàng)目時(shí)并不需要特殊的設(shè)定,可以這么說,項(xiàng)目打包后,直接放到nginx下就可以運(yùn)行。
而history模式則不然,vue官方在介紹history模式時(shí),告知這種模式需要一些配置或者需要后端來支持,所以我們看一下如何配置吧。
第一種 一個(gè)域名,多個(gè)項(xiàng)目
這里我要說的項(xiàng)目滿足下面幾個(gè)條件:
1、前后端分離項(xiàng)目
2、前端項(xiàng)目部署在nginx下,切nginx下為一個(gè)域名 多個(gè)項(xiàng)目。什么意思呢,就是你們的項(xiàng)目是像這樣訪問的:
www.test.com/project1
www.test.com/project2
www.test.com/project3
3、需要Vue-cli 3,請不要把vue的版本和vue-cli的版本混淆。
4、項(xiàng)目中已經(jīng)有了router相關(guān)的依賴,就是在創(chuàng)建項(xiàng)目時(shí),安裝了vue-router。
假設(shè)我們的項(xiàng)目打包目錄是abc,在nginx下需要通過www.test.com/abc這樣訪問,項(xiàng)目的主頁為 www.test.com/abc/home
先配置router.js ,添加下面內(nèi)容:
mode: 'history',
base: '/abc/'
然后在routes里添加下面內(nèi)容
{ path: '/', redirect:'/home'},
第一步是保證項(xiàng)目是history模式和訪問的路徑,第二部是當(dāng)用戶訪問域名時(shí),如果沒有加router路徑,直接跳轉(zhuǎn)到主頁。
配置完成后大概是這樣的

接下來配置vue.config.js
module.exports = { publicPath: '/abc/', outputDir: 'abc', // baseUrl:'/abc/',}
這里要注意的是,publicPath和baseUrl不能同時(shí)存在,vue官方建議使用publicPath代替baseUrl
到這里,vue的配置就完成了。
接下來配置nginx
打開nginx的conf文件 并在 server中添加下面內(nèi)容
location /abc {
index index.html index.htm;
try_files $uri $uri/ /abc/index.html;
}
修改完后記得重啟nginx命令為
/nginx目錄/nginx -t
/nginx目錄/nginx -s reload
這時(shí)候嘗試下面幾個(gè)操作
訪問:www.test.com/abc 看看是否跳轉(zhuǎn)到www.test.com/abc/home 是則成功,不是則配置有問題。
切換項(xiàng)目的頁面,看看是否有502 404 500的現(xiàn)象,資源是否加載正常,是則成功,不是則配置有問題。
訪問nginx上的其它項(xiàng)目,看看靜態(tài)資源文件是否被剛才的配置影響,未影響則成功,影響則配置有問題。
第二種 一個(gè)域名只有一個(gè)項(xiàng)目,訪問域名就等于訪問項(xiàng)目
項(xiàng)目滿足下面幾個(gè)條件:
1、前后端分離項(xiàng)目
2、前端項(xiàng)目部署在nginx下,切nginx下只有一個(gè)項(xiàng)目,意思是nginx的root 路徑就是項(xiàng)目路徑,可以通過域名直接訪問項(xiàng)目。
3、需要Vue-cli 3,請不要把vue的版本和vue-cli的版本混淆。
4、項(xiàng)目中已經(jīng)有了router相關(guān)的依賴,就是在創(chuàng)建項(xiàng)目時(shí),安裝了vue-router。
router.js
參考第一種配置方法中的內(nèi)容,將base修改為'/',修改后如代碼:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
// base: process.env.BASE_URL,
// base: '/abc/',
base: '/',
routes: [
{
path: '/',
redirect:'/home'
},
{
path: '/home',
name: 'home',
component: Home
},
{
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(/* webpackChunkName: "about" */ './views/About.vue')
}
]
})
vue.config.js 參考第一種配置方法中的代碼,修改publicPath為'/',修改后代碼如下:
module.exports = {
// publicPath: '/abc/',
// outputDir: 'abc',
publicPath: '/',
outputDir: 'abc',
}
nginx配置如下,配置location
location / {
root e:\workgit\abc; #項(xiàng)目在服務(wù)器上的真實(shí)路徑
#error_page 405 =200 http://$host:8085/$request_uri;
index index.html index.htm;
try_files $uri $uri/ @rewrites;
}
location @rewrites {
rewrite ^(.*)$ /index.html last;
}
有些項(xiàng)目可能是部署在Apache、Tomcat、IIS下的,請另尋解決方案。
如果有其它問題可以留言。