vue生命周期钩子函数学习笔记

官网详图

涉及到钩子函数有:
1)beforeCreate;
2)created;
3)beforeMount;
4)mounted;
5)beforeUpdate;
6)updated;
7)beforeDestroy;
8)destroyed;
复制一波大佬的代码,这个是我看过最细致的了:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue生命周期学习</title>
  <script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
</head>
<body>
  <div id="app">
    <h1>{{message}}</h1>
  </div>
</body>
<script>
  var vm = new Vue({
    el: '#app',
    data: {
      message: 'Vue的生命周期'
    },
    beforeCreate: function() {
      console.group('------beforeCreate创建前状态------');
      console.log("%c%s", "color:red" , "el     : " + this.$el); //undefined
      console.log("%c%s", "color:red","data   : " + this.$data); //undefined 
      console.log("%c%s", "color:red","message: " + this.message) 
    },
    created: function() {
      console.group('------created创建完毕状态------');
      console.log("%c%s", "color:red","el     : " + this.$el); //undefined
      console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化 
      console.log("%c%s", "color:red","message: " + this.message); //已被初始化
    },
    beforeMount: function() {
      console.group('------beforeMount挂载前状态------');
      console.log("%c%s", "color:red","el     : " + (this.$el)); //已被初始化
      console.log(this.$el);
      console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化  
      console.log("%c%s", "color:red","message: " + this.message); //已被初始化  
    },
    mounted: function() {
      console.group('------mounted 挂载结束状态------');
      console.log("%c%s", "color:red","el     : " + this.$el); //已被初始化
      console.log(this.$el);    
      console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
      console.log("%c%s", "color:red","message: " + this.message); //已被初始化 
    },
    beforeUpdate: function () {
      console.group('beforeUpdate 更新前状态===============》');
      console.log("%c%s", "color:red","el     : " + this.$el);
      console.log(this.$el);   
      console.log("%c%s", "color:red","data   : " + this.$data); 
      console.log("%c%s", "color:red","message: " + this.message); 
    },
    updated: function () {
      console.group('updated 更新完成状态===============》');
      console.log("%c%s", "color:red","el     : " + this.$el);
      console.log(this.$el); 
      console.log("%c%s", "color:red","data   : " + this.$data); 
      console.log("%c%s", "color:red","message: " + this.message); 
    },
    beforeDestroy: function () {
      console.group('beforeDestroy 销毁前状态===============》');
      console.log("%c%s", "color:red","el     : " + this.$el);
      console.log(this.$el);    
      console.log("%c%s", "color:red","data   : " + this.$data); 
      console.log("%c%s", "color:red","message: " + this.message); 
    },
    destroyed: function () {
      console.group('destroyed 销毁完成状态===============》');
      console.log("%c%s", "color:red","el     : " + this.$el);
      console.log(this.$el);  
      console.log("%c%s", "color:red","data   : " + this.$data); 
      console.log("%c%s", "color:red","message: " + this.message)
    }
  })
![屏幕快照 2018-07-28 下午1.55.40.png](https://upload-images.jianshu.io/upload_images/13263206-520675dfb8c9fc03.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</script>
</html>
vue生命周期
一、在beforeCreate和created钩子函数之间的生命周期

       在这个生命周期之间,进行初始化事件,进行数据的观测,可以看到在created的时候数据已经和data属性进行绑定(放在data中的属性当值发生改变的同时,视图也会改变);
注意:此时还是没有el选项;


beforeCreate和created
二、在created和beforeMount钩子函数之间的生命周期
created和beforeMount

       首先会判断对象是否有el选项,如果有的话就继续向下编译,如果没有el选项,则停止编译,也就意味着停止了生命周期,直到在该vue实例上调用vm.$mount(el),此时如果注释掉代码,生命周期就会停止在created:

el: '#app',
注释el

如果我们在后面继续调用vm.$mount(el),可以发现代码继续向下执行了:

vm.$mount(el) //这个el参数就是挂在的dom接点:

注意:此时还是没有el选项
template参数选项的有无对生命周期的影响:
1)如果vue实例对象中有template参数选项,则将其作为模板编译成render函数;
2)如果没有template选项,则将外部HTML作为模板编译;
3)在vue对象中还有一个render函数,它是以createElement作为参数,然后做渲染操作,而且我们可以直接嵌入JSX;
4)template中的模板优先级要高于outer HTML的优先级,所有el的凑数要在template之前了,这是因为vue需要通过el找到对应的outer template;
5)显示排名优先级:render函数选项 > template选项 > outer HTML,即页面中三者同时存在时,只会显示render函数选项,其他两个不显示;


模板渲染优先级
// 模板和外部HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue生命周期学习</title>
  <script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
</head>
<body>
  <div id="app">
    <!--html中修改的-->
    <h1>{{message + '这是在outer HTML中的'}}</h1>
  </div>
</body>
<script>
  var vm = new Vue({
    el: '#app',
    template: "<h1>{{message +'这是在template中的'}}</h1>", //在vue配置项中修改的
    data: {
      message: 'Vue的生命周期'
    }
</script>
</html>
// render函数
new Vue({
    el: '#app',
    render: function(createElement) {
        return createElement('h1', 'this is createElement')
    }
})
三、beforeMount和mounted 钩子函数间的生命周期
beforeMount和mounted

       此时是给vue实例对象添加$el成员,并且替换掉挂载的DOM元素。因为在之前console中打印的结果可以看到beforeMount之前el上还是undefined。


beforeMount和mounted
四、mounted

       在mounted之前h1中还是通过{{message}}进行占位的,因为此时还没有挂载到页面上,还是JavaScript中的虚拟DOM形式存在的,在mounted之后可以看到h1中的内容发生了变化;


mounted
五、beforeUpdate钩子函数和updated钩子函数间的生命周期
beforeUpdate和updated

       当vue发现data中的数据发生了改变,会触发对应组件的重新渲染,先后调用beforeUpdate和updated钩子函数,我们在console中输入:

vm.message = '触发组件更新'

发现触发了组件的更新:


update
六、beforeDestroy和destroyed钩子函数间的生命周期
destroyed

       beforeDestroy钩子函数在实例销毁之前调用,在这一步,实例仍然完全可用;
       destroyed钩子函数在Vue 实例销毁后调用,调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁;

七、created和mounted的区别

       1)created通常是在模板渲染成HTML之前调用,即通常初始化某些属性值,然后再渲染成视图,created使用的次数较多,比如使用chart.js:

var ctx = document.getElementById(ID);

       如果写入组件中,会发现在created中无法对chart进行一些配置,一定要等这个html渲染完后才可以进行,此时无法去操作HTML的dom节点,找不到相关的元素;
       2)mounted是在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作,mounted通常是在一些插件的使用或者组件的使用中进行操作,在mounted中,html已经被渲染出来了,所以可以直接操作dom节点;
       3)created钩子每次加载完成后都可以重复执行;而mounted钩子只在页面第一次加载后才调用出来,只要el被加载过,之后的重复加载该页面就不会调用该钩子了;
注意:mounted在整个实例生命内只执行一次

Vue.component("demo1",{
        data:function(){
            return {
                name:"",
                age:"",
                city:""
            }
        },
        template:"<ul><li id='name'>{{name}}</li><li>{{age}}</li><li>{{city}}</li></ul>",
        created:function(){
            this.name="唐浩益"
            this.age = "12"
            this.city ="杭州"
            var x = document.getElementById("name")//第一个命令台错误,此时无法获取x
            console.log(x.innerHTML);
        },
        mounted:function(){
            var x = document.getElementById("name")//第二个命令台输出结果
            console.log(x.innerHTML);
        }
    });
    var vm = new Vue({
        el:"#example1"
    })

// 使用created会报错
<template lang="jade">
#main(style="width:600px;height:400px;")
</template>

<script>
export default {
  created() {
    this.showChart()
  },
  methods: {
    showChart() {
      var echarts = require('echarts')
      var myChart = echarts.init(document.getElementById('main'))
      // 绘制图表
      myChart.setOption({
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        xAxis: {
          data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      })
    }
  }
}
</script>

<style lang="css">
</style>
created
<template lang="jade">
#main(style="width:600px;height:400px;")
</template>

<script>
export default {
  mounted() {
    this.showChart()
  },
  methods: {
    showChart() {
      var echarts = require('echarts')
      var myChart = echarts.init(document.getElementById('main'))
      // 绘制图表
      myChart.setOption({
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        xAxis: {
          data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      })
    }
  }
}
</script>

<style lang="css">
</style>
mounted
<script>
    // 生命周期函数就是vue实例在某一个时间点会自动执行的函数
    var vm = new Vue({
      el: '#app',
      template: '<div>{{test}}</div>',
      data: {
        test: 'hello world'
      },
      methods: {},
      beforeCreate: function() {
        console.log('beforeCreate');
      },
      created: function() {
        console.log('created');
      },
      beforeMount: function() {
        console.log(this.$el);
        console.log('befordMount');
      },
      mounted: function() {
        console.log(this.$el);
        console.log('mounted');
      },
      beforeUpdate: function() {
        console.log('beforeUpdate');
      },
      updated: function() {
        console.log('updated');
      },
      beforeDestroy: function() {
        console.log('beforeDestroy');
      },
      destroyed: function() {
        console.log('destroyed');
      }
    })
  </script>

参考链接:https://blog.csdn.net/xdnloveme/article/details/78035065
                  https://segmentfault.com/a/1190000011381906

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容