Hi,阿金 ...

路由事件

发表: 2019-03-04 分类:

浏览器路由监听事件

“路由”在任何http框架占有最重要的角色,可以说每个那框架都离不开路由,路由就是框架的核心.
如前端的框架,如前端框架Vue.js,React.js,AngularJS…
PHP框架,Laravel,ThinkPhp,CI…等.

我们今天说的路由,指的前端框架的路由.
因为对vue-router和react-router 4,以这两个路由来实现.
主要的路由事件钩子有:Before,Resolve,After,
[Before 前置]
离开或进入路由,在页面渲染前

[Resolve 确认]
路由已经进行完成,不能修改,不能结束,等待页面渲染结束.

[After 后置]
在页面渲染结束后发生.

Before 前置事件

就是门卫,”从哪儿来到哪儿去的问题”
这门卫还可以给你瞎指路,引导你去.
一般用来做权限验证的.
通过有个全局”门卫”和小部门”门卫”.

Vue:
[参考]

1
2
3
4
5
6
7
8
9
10
11
const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
// ...
//to:去哪的路由信息
//from: 来至哪
//next : 门卫开门指路方法
// 如果没运行next函数,就是门卫懒得不理你.
next();// 给开门了,路自己去找吧吧
next('/login');// 指引你去登记处
})

React:
由于React路由中没有全局中间件,React所有都是组件.
我们可以在根路由组件里面分别实现.

  1. 进入事件
  2. 离开事件
    一般在根组件里面,如监听componentWillReceiveProps事件监听.
    shouldComponentUpdate事件阻断.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React from 'react';
import { Route,Prompt } from 'react-router-dom';
class App extends React.Component {
// 进入事件
componentDidMount(){
let to=this.props.location
let from=undefined;
console.log(to,from);
}
//离开事件
shouldComponentUpdate(nextProps, nextState){
let to=this.props.location
let from=nextProps.location;
console.log(to.pathname,form.pathname);
return true;// 开门
return false;// 不开门
}
}

旧版本路由使用routerWillLeave监听.
新版本react-router v4以后.使用Prompt,由于没有v2版本,这里只例举.Prompt的用法.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React from 'react';
import {Route, Redirect,Prompt} from 'react-router-dom';

class App extends React.Component {

render(){
const HomePage= ()=>(<div>home</div>);
const LoginPage= ()=>(<div>login</div>);
const NotFound= ()=>(<div>404</div>);
return (

<div id="APP">
<Prompt message={(to)=>{
let from=this.props.location;
console.log(to);

return true;// 跳转
return false;// 不跳转
}} />
<Route exact path="/home" component={HomePage}/>
<Route exact path="/login" component={LoginPage}/>
<Route render={NotFound} />
</div>
);
}
}

React中的权限判断最好使用高阶组件来完成.如这样的写法

Resolve 渲染事件

路由已经完成,正在准备渲染了.
vue
通过router.beforeResolve事件来实现.

1
2
3
router.beforeResolve((to, from, next) => {
// ...
})

React
通过组件的生命周期来实现.
render();

1
 

React和Vue区在于,Vue的路由是独立的,而React是组件的;
vue先执行完成路由事件,再去渲染组件,顺序是子路由–>根路由;
React是全部组件从,父级–>子级;

After 渲染事件

vue
vue可以通过,所有路由完成状态

1
2
3
router.afterEach((to, from) => {
// ...
})

react
没有全局钩子,只能约定通过高阶组件来统一管理路由状态.
很难避免直接使用componet的情况.

本文作者:阿金

本文链接:http://www.hi-arkin.com/2019/03/04/Javascript/routerlister/

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

扫描二维码,分享此文章