vue中created和mounted的区别

您所在的位置:网站首页 vue在created请求数据和mounted请求数据区别 vue中created和mounted的区别

vue中created和mounted的区别

#vue中created和mounted的区别| 来源: 网络整理| 查看: 265

一般在项目开发过程中created和mounted生命周期被频繁使用,所以在本文中主要讲解created与mounted在开发中的主要使用区别。

在说明这两个生命周期之前我们先来看一下浏览器的渲染过程:

构建DOM树 构建css规则树,根据执行顺序解析js文件。 构建渲染树Render Tree 渲染树布局layout 渲染树绘制

这里是官方文档对生命周期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'))//

console.log('data:',this.text);//this.text this.sayHello();//this.sayHello() } 复制代码 d生命周期是否获取dom节点是否可以获取data是否获取methodsbeforeCreate否否否created否是是beforeMount否是是mounted是是是

在beforecreate阶段,对浏览器来说,整个渲染流程尚未开始或者说准备开始,对vue来说,实例尚未被初始化,data observer和 event/watcher也还未被调用,在此阶段,对data、methods或文档节点的调用现在无法得到正确的数据。

在created阶段,对浏览器来说,渲染整个HTML文档时,dom节点、css规则树与js文件被解析后,但是没有进入被浏览器render过程,上述资源是尚未挂载在页面上。实例已经被初始化,但是还没有挂载至$el上,所以我们无法获取到对应的节点,但是此时我们是可以获取到vue中data与methods中的数据的。

在beforeMount阶段,实际上与created阶段类似,节点尚未挂载,但是依旧可以获取到data与methods中的数据。

在mounted阶段,对浏览器来说,已经完成了dom与css树的render,并完成对render tree 进行了布局,而浏览器收到这一指令,调用渲染器的paint()在屏幕上显示,而对于vue来说,在mounted阶段,vue的template成功挂载在$el中,此时一个完整的页面已经能够显示在浏览器中,所以在这个阶段,即可以调用节点了(关于这一点,在笔者测试中,在mounted方法中打断点然后run,依旧能够在浏览器中看到整体的页面)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3