Vue的生命周期,有的时候仍是会不熟悉的样子,找了点相关的文章,而后本身尝试着作了点示例,这里记录下,说不定面试就用上了
1.Vue生命周期的相关图片
2.Vue生命周期及路由的钩子函数
实例初始化以后,初始化注入(init injections)及响应(reactivity)前被调用
实例已经建立完成以后被调用,属性已绑定,但DOM还未生成,$el为undefined
这里要视状况来定,根据你的业务来判断是否能够在这里进行ajax请求
在这里以前会根据是否有el元素及是否有内置的template模板来进行选择
没有el则在vm.mounted(el)调用以后再往下执行,没有内置的模板则使用外层的template模板
模板编译、挂载以前,此时$el仍是undefined
实例挂载到页面上,此时能够访问$el
在组件销毁以前调用,这里依然能够访问$el
这里能够作一些重置的操做,好比清除掉组件中的 定时器 和 监听的dom事件
组件销毁
路由导航守卫
要调用next()否则页面会卡在中途
路由进入的时候调用,在组件beforeCreate前
此时尚未组件实例,this为undefined,组件实例尚未被建立
beforeRouteEnter 是支持给 next 传递回调的惟一守卫
对于 beforeRouteUpdate 和 beforeRouteLeave 来讲,this 已经可用了,因此不支持传递回调
在当前路由改变,可是该组件被复用时调用
对于一个带有动态参数的路径 /index/:id,在 /index/1 和 /index/2 之间跳转的时候
因为会渲染一样的 Index 组件,所以组件实例会被复用。而这个钩子就会在这个状况下被调用
离开守卫一般用来禁止用户在还未保存修改前忽然离开,该导航能够经过 next(false) 来取消
3.示例代码
- 我这里是用了webpack打包来作的,并无用new Vue来新建
<script>
export default {
data() {
return {
time: ''
}
},
beforeCreate() {
console.log('beforeCreate: 生命周期之beforeCreate');
console.log(this.$el);
},
created() {
/* 实例已经建立完成以后被调用,属性已绑定,但DOM还未生成,$el为undefined */
console.log('created: 生命周期之created')
console.log(this.$el);
/*
* route是一个跳转的路由对象
* 每个路由都会有一个route对象,是一个局部的对象
* 能够获取对应的name,path,params,query等
* */
console.log(this.$route);
/*
* $router是VueRouter的一个对象
* 经过Vue.use(VueRouter)和VueRouter构造函数获得一个router的实例对象
* 这个对象是一个全局的对象,他包含了全部的路由
* */
console.log(this.$router);
},
beforeMount() {
console.log('beforeMount: 生命周期之beforeMount');
console.log(this.$el);
},
mounted() {
console.log('mounted: 生命周期之mounted');
console.log(this.$el);
this.time = '2018';
},
/* 路由的生命周期 */
beforeRouteEnter(to, from, next) {
/*
* 此时尚未组件实例,this为undefined,组件实例尚未被建立
* beforeRouteEnter 是支持给 next 传递回调的惟一守卫
* 对于 beforeRouteUpdate 和 beforeRouteLeave 来讲,this 已经可用了,因此不支持传递回调
*
* */
console.log('beforeRouteEnter: 进入路由');
/* 在这里用this没法获取vue实例,但能够在next()回调里访问组件实例 */
console.log(this);
/*
* 要调用next()方法
* next()进行管道中的下一个钩子
* 若是所有钩子执行完了,则导航的状态就是 confirmed (确认的)
* */
// next();
/* next()回调里访问组件实例 */
next(vm => {
/* 这里的打印是在mounted以后 */
console.log(vm);
})
},
beforeRouteUpdate(to, from, next) {
console.log('beforeRouteUpdate: 路由更新');
console.log(this.$route);
next();
},
beforeRouteLeave(to, from, next) {
/*
* 离开守卫一般用来禁止用户在还未保存修改前忽然离开
* 该导航能够经过 next(false) 来取消
* 使用next(false),页面依然停留在当前页面,组件的beforeDestroy和destroy生命周期不执行
* */
console.log('beforeRouteLeave: 离开该组件对应的路由');
console.log(this.$route);
next();
// next(false);
},
beforeUpdate() {
console.log('beforeUpdate: 生命周期之beforeUpdate');
console.log(this.$el);
},
updated() {
console.log('updated: 生命周期之updated');
console.log(this.$el);
},
beforeDestroy() {
/* 这里作一些重置的操做,好比清除掉组件中的 定时器 和 监听的dom事件 */
console.log('beforeDestroy: 生命周期之beforeDestroy');
console.log(this.$el);
},
destroyed() {
console.log('destroy: 生命周期之destroy');
console.log(this.$el);
}
}
</script>
输出图片
- 当组件被复用时,路由为/routerIndex?id=1
离开当前路由时
正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯^_^)