vue.js 生命周期详解

vue.js的生命周期是很是重要的一个点,听起来是老生常谈了。但若是仅仅是知道它有哪几个生命周期是远远不够的。
要清楚了解每一个周期钩子在干什么,什么事情该使用哪一个钩子干,这样才能更清晰的开发,避免踩坑
vue的生命周期有8个钩子函数,分别为建立前/后,挂载前/后,更新前/后,销毁前/后。html


clipboard.png
这是官方文档的图,下面有代码来详细了解一下各个钩子vue

beforeCreate: function beforeCreate() {
    //do something before creating vue instance
    console.log('---------被建立前----------');
    console.log('data: ',this.$data);
    console.log('$el: ',this.$el)
  },
  created: function created() {
    //do something after creating vue instance
    console.log('---------被建立完成---------');
    console.log('data: ',this.$data);
    console.log('$el: ',this.$el);
    console.log('root: ',this.$root)

  },
  beforeMount: function beforeMount() {
    //do something before mounting vue instance
    console.log('----------被挂载前----------')
    console.log('data: ',this.$data);
    console.log('$el: ',this.$el)
    console.log('root: ',this.$root)
  },
  mounted: function mounted() {
  //do something after mounting vue instance
    console.log('----------被挂载后---------')
    console.log('data: ',this.$data);
    console.log('$el: ',this.$el)
    console.log('root: ',this.$root)
  }

$el:当前组件的元素,也就是templa的根元素
data:组件里的data对象
代码执行的结果如图dom

clipboard.png
这几个钩子的分工
1.beforeCreate: 建立组件前先获取数据,初始化事件,获取不到data,$el
2.created:建立组件后,能够获取了数据data,可是依旧没有挂载元素
3.beforeMounted:挂载前,获取不到root,$el,获取不到dom,能够获取data
4.mounted:挂载后,将编译好的模板挂载到html上,获取获取dom,root,在这个钩子里执行对dom修改的方法
5.beforeUpdate和updated:很容易理解,就是某些行为发生后数据改变先后的钩子
6.beforeDestroyed和destroyed:组件销毁先后的钩子函数

相关文章
相关标签/搜索