浏览器history模式及Umi history的使用

history API 是 H5 提供的新特性,允许开发者直接更改前端路由,即更新浏览器 URL 地址而不重新发起请求。它提供了丰富的函数供开发者调用:

push :向 history 栈里添加一条新记录,用户点击浏览器的回退按钮可以回到之前的路径;

go:在 history 记录中向前或者后退多少步,参数是一个整数,可为正数可为负数;

goBack:返回上一页;

forward():前进;

replace:替换当前的 history 记录,跳转到指定的 url,不会向 history 添加新的记录,点击返回,会跳转到上一个页面,上一个记录是不存在的;

常用示例:

location.reload() 刷新

history.go(1) 前进

history.go(-1) 后退

history.forward() 前进

history.back() 后退 + 刷新

扩展:

history.back 与 history.go 的区别:

history.back(-1) 直接返回当前页的上一页,数据全部消息,是个新页面

history.go(-1) 也是返回当前页的上一页,不过表单里的数据全部还在

Umi中history 相关实用API

1、获取当路由信息

import { history } from 'umi';

// history 栈的实体个数
console.log(history.length);

// 当前 history 跳转的action, 有push/replace/pop 三种类型
console.log(history.action)

// location 对象,包含 pathname/search/hash
console.log(history.location.pathname)
console.log(history.location.search)
console.log(history.location.hash)

2、路由跳转

import { history } from 'umi';

// 跳转到指定路由
history.push('/list')

// 带参数跳转到指定路由
history.push('/list?a=b')
history.push({
  pathname: '/list',
  query: {
    a: 'b'
  }
})

// 跳转到上一个路由
history.goBack();

3、路由实时监听

import { history } from 'umi';

const unlisten = history.listen((location, action) => {
  console.log(location.pathname)
})
unlisten()


未经允许不得转载:Web前端开发资源网 » 浏览器history模式及Umi history的使用

推荐阅读:

Z-Blog后台无法安装、更新应用的解决方法

使用float后清除浮动的几种方法

找回Windows Server&Windows10 ltsb 图片查看器

input[type=file]去掉“未选择任何文件”及样式改进

WebStorm绑定Chrome浏览器实现实时自动刷新

赞 (2)
分享到: +

评论 沙发

Avatar

换个身份

  • 昵称 (必填)
  • 邮箱 (选填)