訪問vue頁面時,/# 使url看著不美觀,使用 H5 history模式可以完美解決這個問題,但需要后端nginx幫助。接下來我們自己配置一下。
使用前端路由,但切換新路由時,想要滾動到頁面頂部,或者保持原先的滾動位置,就像重新加載頁面那樣,vue-router 可以讓你自定義路由切換頁面時如何滾動。
當創建Router實例時,可以提供一個 scrollBehavior 方法:
const router = new VueRouter({routes: [...],mode: 'history', //H5 history模式scrollBehavior (to, from, savedPosition) {// return 期望滾動到哪個的位置return { x: 0, y: 0 } //讓頁面滾動到頂部}
})
復制代碼
更多滾動行為實例可以參考官網 router.vuejs.org/zh/guide/ad…
打包之后會造成一個問題,刷新打包文件頁面 ,會出現404頁面空白,接下來需要配置一下nginx文件,就可以訪問打包后的文件了。
vue單頁面的啟動頁面是index.html文件,路由實際是不存在的,所以會出現頁面刷新404問題,需要設置一下訪問vue頁面映射到index.html上。
首先,我們需要確定一下打包靜態資源的路徑需要設置絕對路徑
config/index.js
build: {assetsPublicPath: '/'
}
復制代碼
然后配置一下nginx映射問題
location / {root /www/dist;index index.html index.htm;try_files $uri $uri/ /index.html; //映射到index.html上
}
復制代碼
醬紫就可以訪問啦。
有同學可能會遇到 nginx 配置pc端、移動端自動跳轉的問題, 接下來我們配置一下。
http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80;server_name www.baidu.com; //服務器網址set $mobile_rewrite do_not_perform; //設置pc重定向if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os )?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino") {set $mobile_rewrite perform;} //設置移動端重定向location / {root /www/dist/m; //移動端rootif ($mobile_rewrite = do_not_perform) { //根據重定向 重置 rootroot /www/dist; //pc端root}index index.html index.htm;try_files $uri $uri/ /index.html; //映射到index.html上}location ~ ^/api {proxy_set_header Host $http_host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_pass http://unix:/home/dev/official/official.sock;proxy_max_temp_file_size 2m;proxy_connect_timeout 90;proxy_send_timeout 90;proxy_read_timeout 90;proxy_buffer_size 4k;proxy_buffers 4 32k;proxy_busy_buffers_size 64k;proxy_temp_file_write_size 64k;client_max_body_size 5m;} error_page 404 http://www.baidu.com;error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
復制代碼
醬紫就可以使用同一網址同時訪問移動端和pc端項目啦。
有些地方可能表述的不夠清晰,又不懂的地方可以留言,我看到知道后一定會及時回答的。