前言
关于vue.js中的生命周期,如果不是有特别的需求,一般在项目开发过程中更多的使用created和mounted,
所以在本文中主要讲解created与mounted在开发中的主要使用区别。
关于完整的生命周期,不久会在另一篇文章中做整体的理解,包括activated、destroyed等,不过可能会有点晚,大家可以留意一下
版本信息:
系统:win10 Vue:2.5.2 webpack:3.6.0 npm:6.9.0 node:10.15.3生命周期
完整的生命周期图示为了避免占用板块,这里就不贴出来了,大家可以自行前往vue生命周期查看。
浏览器渲染过程
具体的浏览器渲染过程我会过几天另外写一遍文章,大家可以去我的文章看看。
生命周期中的浏览器渲染
这里是官方文档对生命周期api的解释,大家可以看看
以下为测试vue部分生命函数
beforeCreate(){ console.log('beforecreate:',document.getElementById('first'))//null console.log('data:',this.text);//undefined this.sayHello();//error:not a function},created(){ console.log('create:',document.getElementById('first'))//null console.log('data:',this.text);//this.text this.sayHello();//this.sayHello()},beforeMount(){ console.log('beforeMount:',document.getElementById('first'))//null console.log('data:',this.text);//this.text this.sayHello();//this.sayHello()},mounted(){ console.log('mounted:',document.getElementById('first'))//<p></p> console.log('data:',this.text);//this.text this.sayHello();//this.sayHello()}
通过上述测试我们可以知道,
生命周期 | 是否获取dom节点 | 是否可以获取data | 是否获取methods |
---|---|---|---|
beforeCreate | 否 | 否 | 否 |
created | 否 | 是 | 是 |
beforeMount | 否 | 是 | 是 |
mounted | 是 | 是 | 是 |
以我的个人理解,vue生命周期实际上和浏览器渲染过程是挂钩的,
在beforecreate阶段,对浏览器来说,整个渲染流程尚未开始或者说准备开始,对vue来说,实例尚未被初始化,data observer和 event/watcher也还未被调用,在此阶段,对data、methods或文档节点的调用现在无法得到正确的数据。
在created阶段,对浏览器来说,渲染整个HTML文档时,dom节点、css规则树与js文件被解析后,但是没有进入被浏览器render过程,上述资源是尚未挂载在页面上,也就是在vue生命周期中对应的created
新闻热点
疑难解答
图片精选