vue-router路由history模式

647 阅读1分钟

理论

history api 的两个新方replaceStatepushState 两个方法参数一样 params { 

  •   state:存储JSON字符串,可以用在popstate事件中,可以通过locaton.state获取。

  •   title:现在大多数浏览器不支持或者忽略这个参数,最好用null代替

  •   url:任意有效的URL,用于更新浏览器的地址栏,并不在乎URL是否已经存在地址列表中。更重要的是,它不会重新加载页面。 }

    两个方法等价于this.router.push()this.router.push() 和 this.router.replace()

  • 用于往history的堆栈 替换或者 添加 记录

  • 注意只有在浏览器点击前进后退(或者调用history.back,forward,go)才能触发popstate事件

    window.addEventListener('popstate', function(event){
        var state = history.state || event.state || window.event.state;
        console.log("state被触发",state)

    },false);
好处:触发时候可以传递参数,并且页面不刷新页面。
服务器配置所有请求都返回index.html,是为了给spa页面能正常加载所有信息,然后再处理路由信息。

1.router配置

//设置mode路由模式
export default new Router({
  mode: 'history'
  ...
})

2.路由-所有错误地址-重定向redirect

//设置mode路由模式
export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect:'index',
    },
     {
        path: '/index',
        name:'index',
        component: () => import("@/views/index.vue"),
    },
    {
      path: '*', //所有错误的请求都回到首页
      redirect: "/"
    },
  ]
}

3.vue.config.js配置

module.exports = {
// 默认就是'/',当访问多个 / ,如: http://10.10.xxx.xxx:8011/login/test/22 也能正常访问到 对应的js资源 
  publicPath: '/', 
  },

4.1 nginx错误地址重定向

    server {
        listen       8011;
        server_name 10.xxx.xxx.xx;
	location / {
            root   html/;
            index  index.html index.htm;
            add_header Access-Control-Allow-Origin *;//跨域处理
            try_files $uri $uri/ /index.html;//当无当前地址,重定向到首页
        }
    }

4.2 tomcat错误地址重定向

部署文件:

/WEB-INF/web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app metadata-complete="true" version="3.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee">
    <display-name>Router for Tomcat</display-name>
    <error-page>
    <error-code>404</error-code>
    <location>/</location>
    </error-page>
    </web-app>