Home > Article > Web Front-end > A detailed introduction to hook functions in Vue
The content shared with you in this article is about Vue’s hook functions [route navigation guard, keep-alive, life cycle hook]. It has certain reference value. Friends in need can refer to it.
When it comes to Vue’s hook functions, many people may only stick to some very simple and commonly used hooks (created
,mounted
). Moreover, I have not studied the differences carefully, and when to use which hook. Moreover, Vue’s life cycle is also a relatively frequent test point in interviews. So how to answer such questions will make people confused. It feels bright...
Sometimes, we need to perform some operations through routing, such as the most common login permission verification. When the user meets the conditions , let them enter the navigation, otherwise cancel the jump and jump to the login page to let them log in.
For this reason, we have many ways to embed the routing navigation process: Global, exclusive to a single route, or component-level, it is recommended to read the routing document first
vue-router has three guards globally:
router.beforeEach global front guard before entering the route
router.beforeResolve Global parsing guard (2.5.0) Called after beforeRouteEnter is called
router.afterEach After the global post hook enters the route
Usage method:
// main.js 入口文件 import router from './router'; // 引入路由 router.beforeEach((to, from, next) => { next(); }); router.beforeResolve((to, from, next) => { next(); }); router.afterEach((to, from) => { console.log('afterEach 全局后置钩子'); });
to and from are routing objects that will enter and leave, the routing object refers to the routing object usually obtained through this.$route.
next:Function This parameter is a function, and must be called, otherwise the route cannot be entered (the page is blank).
next() Enter the route.
next(false): Cancel the entry route and reset the url address to the from routing address (that is, the routing address to be left).
next jumps to a new route, the current navigation is interrupted, and a new navigation is started again.
We can jump like this: next('path address') or next({path:''}) or next({name:''})
and allow settings such as replace: true, Options like name: 'home'
and the object options you use in router-link or router.push.
If you don’t want to configure guards globally, you can configure guards separately for certain routes:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // 参数用法什么的都一样,调用顺序在全局前置守卫后面,所以不会被全局守卫覆盖 // ... } } ] })
beforeRouteEnter Before entering the route
beforeRouteUpdate (2.2) When the route reuses the same component
beforeRouteLeave When leaving the current route
Introduction in the document:
beforeRouteEnter (to, from, next) { // 在路由独享守卫后调用 不!能!获取组件实例 `this`,组件实例还没被创建 }, beforeRouteUpdate (to, from, next) { // 在当前路由改变,但是该组件被复用时调用 可以访问组件实例 `this` // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用,可以访问组件实例 `this` }
beforeRouteEnter access this
Because the hook is called before the component instance is created, the component instance this
cannot be obtained. You can access the component instance by passing a callback to
next
.
But the execution timing of the callback is after mounted, so in my opinion the access to this here is not very meaningful, it can be placed in created
or mounted
inside.
beforeRouteEnter (to, from, next) { console.log('在路由独享守卫后调用'); next(vm => { // 通过 `vm` 访问组件实例`this` 执行回调的时机在mounted后面, }) }
beforeRouteLeave:
Called when the navigation leaves the corresponding route of this component. We use it to prevent the user from leaving, such as before saving the draft, or before the user leaves. , destroy setInterval
to prevent the timer from still being called after leaving.
beforeRouteLeave (to, from , next) { if (文章保存) { next(); // 允许离开或者可以跳到别的路由 上面讲过了 } else { next(false); // 取消离开 } }
If we have in the hook function of global guard/route exclusive guard/component route guard Errors can be captured like this:
router.onError(callback => { // 2.4.0新增 并不常用,了解一下就可以了 console.log(callback, 'callback'); });
There are more instance methods in the routing document: dynamically adding routes, etc. If you are interested, you can learn about it.
I understand that many people will encounter this problem, take a look at this pseudo code:
router.beforeEach((to, from, next) => { if(登录){ next() }else{ next({ name: 'login' }); } });
Look at the logic It seems to be correct, but when we jump to login
, because we are still not logged in at this time, we will keep jumping to login
and then loop endlessly, and the page will always be blank. , so: we need to change the judgment conditions slightly.
if(登录 || to.name === 'login'){ next() } // 登录,或者将要前往login页面的时候,就允许进入路由
The document mentions that because router.afterEach does not accept the next
function, it will not change the navigation itself, which means that only It can be used as a hook, but when I tried it, I found that we can achieve the jump in this form:
// main.js 入口文件 import router from './router'; // 引入路由 router.afterEach((to, from) => { if (未登录 && to.name !== 'login') { router.push({ name: 'login' }); // 跳转login } });
Well, it can also be achieved and better through router.beforeEach, so I just Show off.
Trigger entry to other routes.
Call the component guard to leave the routebeforeRouteLeave
Call the pre-guard: beforeEach
Call in the reused componentbeforeRouteUpdate
Call the route exclusive guardbeforeEnter
.
解析异步路由组件。
在将要进入的路由组件中调用beforeRouteEnter
调用全局解析守卫 beforeResolve
导航被确认。
调用全局后置钩子的 afterEach
钩子。
触发DOM更新(mounted
)。
执行beforeRouteEnter
守卫中传给 next 的回调函数
在开发Vue项目的时候,大部分组件是没必要多次渲染的,所以Vue提供了一个内置组件keep-alive
来缓存组件内部状态,避免重新渲染,文档在这里。
文档:和<transition>
相似,<keep-alive>
是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。
缓存动态组件:
<keep-alive>
包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们,此种方式并无太大的实用意义。
<!-- 基本 --> <keep-alive> <component :is="view"></component> </keep-alive> <!-- 多个条件判断的子组件 --> <keep-alive> <comp-a v-if="a > 1"></comp-a> <comp-b v-else></comp-b> </keep-alive>
缓存路由组件:
使用keep-alive
可以将所有路径匹配到的路由组件都缓存起来,包括路由组件里面的组件,keep-alive
大多数使用场景就是这种。
<keep-alive> <router-view></router-view> </keeo-alive>
这篇既然是Vue钩子函数的专场,那肯定要扣题呀~
在被keep-alive
包含的组件/路由中,会多出两个生命周期的钩子:activated
与 deactivated
。
文档:在 2.2.0 及其更高版本中,activated 和 deactivated 将会在 <keep-alive> 树内的所有嵌套组件中触发。
activated在组件第一次渲染时会被调用,之后在每次缓存组件被激活时调用。
activated调用时机:
第一次进入缓存路由/组件,在mounted
后面,beforeRouteEnter
守卫传给 next 的回调函数之前调用:
beforeMount=> 如果你是从别的路由/组件进来(组件销毁destroyed/或离开缓存deactivated)=> mounted=> activated 进入缓存组件 => 执行 beforeRouteEnter回调
因为组件被缓存了,再次进入缓存路由/组件时,不会触发这些钩子:
// beforeCreate created beforeMount mounted 都不会触发。
所以之后的调用时机是:
组件销毁destroyed/或离开缓存deactivated => activated 进入当前缓存组件 => 执行 beforeRouteEnter回调 // 组件缓存或销毁,嵌套组件的销毁和缓存也在这里触发
deactivated:组件被停用(离开路由)时调用
使用了keep-alive
就不会调用beforeDestroy
(组件销毁前钩子)和destroyed
(组件销毁),因为组件没被销毁,被缓存起来了。
这个钩子可以看作beforeDestroy
的替代,如果你缓存了组件,要在组件销毁的的时候做一些事情,你可以放在这个钩子里。
如果你离开了路由,会依次触发:
组件内的离开当前路由钩子beforeRouteLeave => 路由前置守卫 beforeEach => 全局后置钩子afterEach => deactivated 离开缓存组件 => activated 进入缓存组件(如果你进入的也是缓存路由) // 如果离开的组件没有缓存的话 beforeDestroy会替换deactivated // 如果进入的路由也没有缓存的话 全局后置钩子afterEach=>销毁 destroyed=> beforeCreate等
那么,如果我只是想缓存其中几个路由/组件,那该怎么做?
想实现类似的操作,你可以:
配置一下路由元信息
创建两个keep-alive
标签
使用v-if
通过路由元信息判断缓存哪些路由。
<keep-alive>
<router-view v-if="$route.meta.keepAlive"> <!--这里是会被缓存的路由--> </router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"> <!--因为用的是v-if 所以下面还要创建一个未缓存的路由视图出口--> </router-view> //router配置 new Router({ routes: [ { path: '/', name: 'home', component: Home, meta: { keepAlive: true // 需要被缓存 } }, { path: '/:id', name: 'edit', component: Edit, meta: { keepAlive: false // 不需要被缓存 } } ] });
使用路由元信息的方式,要多创建一个router-view
标签,并且每个路由都要配置一个元信息,是可以实现我们想要的效果,但是过于繁琐了点。
幸运的是在Vue2.1.0之后,Vue新增了两个属性配合keep-alive
来有条件地缓存 路由/组件。
新增属性:
include
:匹配的 路由/组件 会被缓存
exclude
:匹配的 路由/组件 不会被缓存
include
和exclude
支持三种方式来有条件的缓存路由:采用逗号分隔的字符串形式,正则形式,数组形式。
正则和数组形式,必须采用v-bind
形式来使用。
缓存组件的使用方式:
<!-- 逗号分隔字符串 --> <keep-alive include="a,b"> <component :is="view"></component> </keep-alive> <!-- 正则表达式 (使用 `v-bind`) --> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive> <!-- 数组 (使用 `v-bind`) --> <keep-alive :include="['a', 'b']"> <component :is="view"></component> </keep-alive>
但更多场景中,我们会使用keep-alive
来缓存路由:
<keep-alive include='a'> <router-view></router-view> </keeo-alive>
匹配规则:
首先匹配组件的name选项,如果name
选项不可用。
则匹配它的局部注册名称。 (父组件 components
选项的键值)
匿名组件,不可匹配。
比如路由组件没有name
选项,并且没有注册的组件名。
只能匹配当前被包裹的组件,不能匹配更下面嵌套的子组件。
比如用在路由上,只能匹配路由组件的name
选项,不能匹配路由组件里面的嵌套组件的name
选项。
文档:<keep-alive>
不会在函数式组件中正常工作,因为它们没有缓存实例。
exclude
的优先级大于include
也就是说:当include
和exclude
同时存在时,exclude
生效,include
不生效。
<keep-alive include="a,b" exclude="a"> <!--只有a不被缓存--> <router-view></router-view> </keep-alive>
当组件被exclude
匹配,该组件将不会被缓存,不会调用activated
和 deactivated
。
关于组件的生命周期,是时候放出这张图片了:
这张图片已经讲得很清楚了,很多人这部分也很清楚了,大部分生命周期并不会用到,这里提一下几点:
ajax请求最好放在created
里面,因为此时已经可以访问this
了,请求到数据就可以直接放在data
里面。
这里也碰到过几次,面试官问:ajax请求应该放在哪个生命周期。
关于dom的操作要放在mounted
里面,在mounted
前面访问dom会是undefined
。
每次进入/离开组件都要做一些事情,用什么钩子:
不缓存:
进入的时候可以用created
和mounted
钩子,离开的时候用beforeDestory
和destroyed
钩子,beforeDestory
可以访问this
,destroyed
不可以访问this
。
缓存了组件:
缓存了组件之后,再次进入组件不会触发beforeCreate
、created
、beforeMount
、 mounted
,如果你想每次进入组件都做一些事情的话,你可以放在activated
进入缓存组件的钩子中。
同理:离开缓存组件的时候,beforeDestroy
和destroyed
并不会触发,可以使用deactivated
离开缓存组件的钩子来代替。
将路由导航、keep-alive
、和组件生命周期钩子结合起来的,触发顺序,假设是从a组件离开,第一次进入b组件:
beforeRouteLeave
:路由组件的组件离开路由前钩子,可取消路由离开。
beforeEach
: 路由全局前置守卫,可用于登录验证、全局路由loading等。
beforeEnter
: 路由独享守卫
beforeRouteEnter
: 路由组件的组件进入路由前钩子。
beforeResolve
:路由全局解析守卫
afterEach
:路由全局后置钩子
beforeCreate
:组件生命周期,不能访问this
。
created
:组件生命周期,可以访问this
,不能访问dom。
beforeMount
:组件生命周期
deactivated
: 离开缓存组件a,或者触发a的beforeDestroy
和destroyed
组件销毁钩子。
mounted
:访问/操作dom。
activated
:进入缓存组件,进入a的嵌套子组件(如果有的话)。
执行beforeRouteEnter回调函数next。
Vue提供了很多钩子,但很多钩子我们几乎不会用到,只有清楚这些钩子函数的触发顺序以及背后的一些限制等,这样我们才能够正确的使用这些钩子,希望看了本文的同学,能对这些钩子有更加清晰的认识,使用起来更加得心应手。
相关推荐:
AngularJs中model、Controller(控制器)和View(视图)之间有什么样的关系?(图文)
The above is the detailed content of A detailed introduction to hook functions in Vue. For more information, please follow other related articles on the PHP Chinese website!