VUE项目地址去掉 # 号的方法

 4238

VUE项目地址去掉 # 号的方法,vue 项目往往会搭配 vue-router 官方路由管理器,它和 vue.js 的核心深度集成,让构建单页面应用变得易如反掌。vue-router 默认为 hash 模式,使用 URL 的 hash 来模拟一个完整的 URL,所以当 URL 改变时,页面不会重新加载,只是根据 hash 来更换显示对应的组件,这就是所谓的单页面应用。

但是使用默认的 hash 模式时,浏览器 URL 地址中会有一个 # ,这跟以往的网站地址不太一样,可能也会让大部分人不习惯,甚至觉得它很丑。

想要去掉地址中的 # 也不难,只要更换 vue-router 的另一个模式 history 模式即可做到。如下:


5f014ee20b862.jpg


当你使用 history 模式时,URL 就变回正常又好看的地址了,和大部分网站地址一样,例如:http://zztuku.com/name/id

不过,这种模式有个坑,不仅需要前端开发人员将模式改为 history 模式,还需要后端进行相应的配置。如果后端没有正确的配置好,当你访问你的项目地址时,就会出现 404 ,这样可就更不好看了。


官方给出了几种常用的后端配置例子:

Apache:

  1. <IfModule mod_rewrite.c>
  2.   RewriteEngine On
  3.   RewriteBase /
  4.   RewriteRule ^index\.html$ - [L]
  5.   RewriteCond %{REQUEST_FILENAME} !-f
  6.   RewriteCond %{REQUEST_FILENAME} !-d
  7.   RewriteRule . /index.html [L]
  8. </IfModule>

Nginx:

  1. location / {
  2.   try_files $uri $uri/ /index.html;
  3. }

原生 Node.js

  1. const http = require('http')
  2. const fs = require('fs')
  3. const httpPort = 80
  4. http.createServer((req, res) => {
  5.   fs.readFile('index.htm', 'utf-8', (err, content) => {
  6.     if (err) {
  7.       console.log('We cannot open "index.htm" file.')
  8.     }
  9.     res.writeHead(200, {
  10.       'Content-Type': 'text/html; charset=utf-8'
  11.     })
  12.     res.end(content)
  13.   })
  14. }).listen(httpPort, () => {
  15.   console.log('Server listening on: http://localhost:%s', httpPort)
  16. })

IIS:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3.   <system.webServer>
  4.     <rewrite>
  5.       <rules>
  6.         <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
  7.           <match url="(.*)" />
  8.           <conditions logicalGrouping="MatchAll">
  9.             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  10.             <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  11.           </conditions>
  12.           <action type="Rewrite" url="/" />
  13.         </rule>
  14.       </rules>
  15.     </rewrite>
  16.   </system.webServer>
  17. </configuration>

Caddy:

  1. rewrite {
  2.     regexp .*
  3.     to {path} /
  4. }

Firebase 主机:

在你的 firebase.json 中加入:

  1. {
  2.   "hosting": {
  3.     "public": "dist",
  4.     "rewrites": [
  5.       {
  6.         "source": "**",
  7.         "destination": "/index.html"
  8.       }
  9.     ]
  10.   }
  11. }

以上,就是VUE项目地址去掉 # 号的方法,更多也可以参考:https://router.vuejs.org/zh/guide/essentials/history-mode.html



TAG标签:
本文网址:https://www.zztuku.com/detail-7872.html
站长图库 - VUE项目地址去掉 # 号的方法
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐