vue也有自己的生命周期。数据初始化的生命周期如下:
beforeCreate、created、beforeMount、mounted
1.beforeCreate
此时,无法通过vm访问data中的数据,methods中的方法。
2.created
此时,可以通过vm访问到data中的数据,methods中配置的方法。
3.beforeMount
此时,页面呈现的是未经vue编译的DOM结构,所有dom操作均不生效。
4.mounted
页面中呈现的是经过Vue编译的DOM,对dom的操作均有效,一般在次进行开启定时器、发送网络请求、订阅消息、绑定自定义事件等。
vue完成模板的解析并把初始的真实dom元素放入页面后(挂载完毕)调用mounted
参考代码:
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 27 28 29 30 31 32 33 34 35 36 37 38 39 | <! DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >vue测试</ title > </ head > < body > < div id = "root" > < h2 > </ h2 > </ div > < script type = "text/javascript" > new Vue({ el: '#root', data: { }, beforeCreate() { console.log("beforeCreate") }, created() { console.log("created") }, beforeMount() { console.log("beforeMount") }, mounted() { console.log("mounted") }, }) </ script > </ body > </ html > |
执行后F12看到的顺序:
