Vue路由模式(history模式 刷新页面空白解决方案)


前言

vue路由的三种模式 Hash模式History模式abstract 模式

一、Hash模式

  • Vue3:
  • Hash 模式是用 createWebHashHistory() 创建的:
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: [
		//...
	]
})

它在内部传递的实际 URL 之前使用了一个哈希字符(#)。由于这部分 URL 从未被发送到服务器,所以它不需要在服务器层面上进行任何特殊处理。不过,它在 SEO 中确实有不好的影响。如果你担心这个问题,可以使用 HTML5 模式。

二、HTML5 (History)模式

  • Vue3
  • History模式是用 createWebHashHistory() 创建的:
import {
    
     createRouter, createWebHashHistory } 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(); //前进

不过,问题来了。由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/id,就会得到下图 404 的错误。这就尴尬了。404 Not Found

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否则会出现vue的路由在nginx中刷新出现404
     index index.html index.htm;
 }
 #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
 #因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
    rewrite ^.*$ /index.html last; # /index.html 为项目根目录
}

2、Internet Information Services (IIS)配置

a、安装 IIS UrlRewrite

b、在网站的根目录下创建一个 web.config 文件,内容如下:

<?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的环境中,暂未实际使用过,后期补充相关实现

  • Vue3
  • 在 SSR 上使用时,你需要手动传递相应的 history:
  • Abstract 模式是用 createMemoryHistory() 创建的:
// router.js
let history = isServer ? createMemoryHistory() : createWebHistory()
let router = createRouter({
    
     routes, history })
// 在你的 server-entry.js 中的某个地方
router.push(req.url) // 请求 url
router.isReady().then(() => {
    
    
  // 处理请求
})

总结

以上就是Vue不同的历史模式内容,本文简单介绍了Vue History路由模式的使用,而具体的项目配置需根据项目实际情况配置。

感谢阅读!
参考:Vue路由的不同的历史模式

猜你喜欢

转载自blog.csdn.net/weiCong_Ling/article/details/130618357