初学vue之钩子函数总结

一、什么是钩子函数

      钩子的概念源于Windows的消息处理机制,通过设置钩子,应用程序可以对所有的消息事件进行拦截,然后执行钩子函数,对消息进行想要的处理方式。以下是常用的一些钩子函数。

二、常用的钩子函数

2.1 常用钩子函数调用时机

    beforeCreate====组件实例化之前执行的函数

    created========组件实例化完毕,但页面还未显示

    beforeMount====组件挂载前,页面仍未显示,但虚拟Dom已经配置

    mounted=======组件挂载后,此方法执行后,页面显示

    beforeUpdate===组件更新前,页面仍未更新,但虚拟Dom已经配置

    updated=======组件更新,此方法执行后,页面显示

    beforeDestory===组件销毁前

    destoryed======组件销毁

参考:vue钩子函数的调用时机详述
2.2 常用钩子函数使用举例

1)beforeCreate

这个时候,this变量还不能使用,在data下的数据,和methods下的方法,watcher中的事件都不能获得到;

import Vue from 'vue';

Vue.component('Test', {
  props: {
    name: String
  },
  template: `<div class="test">{{ name }}</div>`,
  beforeCreate() {
    console.log('Test beforeCreate');
  },
  created() {
    console.log('Test created');
  },
  mounted() {
    console.log('Test mounted');
  },
  beforeDestroy() {
    console.log('Test beforeDestroy');
  },
  destroyed() {
    console.log('Test destroyed');
  },
  beforeUpdate() {
    console.log('Test beforeUpdate');
  },
  updated() {
    console.log('Test updated');
  }
});

Vue.component('Test1', {
  props: {
    name: String
  },
  template: '<div class="test1"><slot />{{ name }}</div>',
  beforeCreate() {
    console.log('Test1 beforeCreate');
  },
  created() {
    console.log('Test1 created');
  },
  mounted() {
    console.log('Test1 mounted');
  },
  beforeDestroy() {
    console.log('Test1 beforeDestroy');
  },
  destroyed() {
    console.log('Test1 destroyed');
  },
  beforeUpdate() {
    console.log('Test1 beforeUpdate');
  },
  updated() {
    console.log('Test1 updated');
  }
});

new Vue({
  el: '#app',
  data() {
    return {
      a: true,
      name: ''
    };
  },
  mounted() {
    setTimeout(() => {
      console.log('-----------');
      this.name = 'yibuyisheng1';
      this.$nextTick(() => {
        console.log('-----------');
      });
    }, 1000);

    setTimeout(() => {
      console.log('-----------');
      this.a = false;
      this.$nextTick(() => {
        console.log('-----------');
      });
    }, 2000);
  },
  template: '<Test1 v-if="a" :name="name"><Test :name="name" /></Test1><span v-else></span>'
});

2)created

这个时候可以操作vue实例中的数据和各种方法,但是还不能对"dom"节点进行操作;

  ...,
  created() {
    let btn = document.querySelector('button')
    console.log(btn.innerText)  //此时找不到button节点,打印不出来button的值
  }

3)mounted

这个时候挂载完毕,这时dom节点被渲染到文档内,一些需要dom的操作在此时才能正常进行。
注意:mounted在整个实例的生命周期中只执行一次。

  ...,
  mounted() {
    let btn = document.querySelector('button')
    console.log(btn.innerText)  //此时可以打印出来button的值
  }

4)computed

是把所有需要依赖其他值计算的值写成对象的key值。

  data() {
    return {
      count: 1
    }
  },
 computed: {
    //是最后需要计算的值,而这个值依赖this.count 
    //那么这个值要写在对象的key值的位置
    countDouble: {
      get: function() {
        return this.count * 2
      },
      set: function(newValue) {
        this.countDouble = newValue
      }
    }   
  }

这时候模板渲染的{{countDouble}}这个值是2

注意:通过计算的countDouble这个变量不需要在data里面声明,如果声明了就会报错

5)watch

把监听的值写成对象的key值

 data() {
    return {
      count: 1
    }
  },
  watch: {
    count: (val, oldVal) => {
      console.log('new: %s, old: %s', val, oldVal)
    }
  }

这时候如果this.count发生了改变,那么监听count变量发生变化的function就会被执行

注意:需要监听的这个变量需要在data里面声明,如果不声明就会报错

三、钩子函数生命周期

vue生命周期简介

clipboard.png

f847b38a-63fe-11e6-9c29-38e58d46f036.png

咱们从上图可以很明显的看出现在vue2.0都包括了哪些生命周期的函数了。

生命周期探究

对于执行顺序和什么时候执行,看上面两个图基本有个了解了。下面我们将结合代码去看看钩子函数的执行。

ps:下面代码可以直接复制出去执行
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/vue/2.1.3/vue.js"></script>
</head>
<body>

<div id="app">
     <p>{{ message }}</p>
</div>

<script type="text/javascript">
    
  var app = new Vue({
      el: '#app',
      data: {
          message : "xuxiao is boy" 
      },
       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)
        }
    })
</script>
</body>
</html>

create 和 mounted 相关

咱们在chrome浏览器里打开,F12console就能发现

beforecreated:el 和 data 并未初始化 
created:完成了 data 数据的初始化,el没有
beforeMount:完成了 el 和 data 初始化 
mounted :完成挂载

另外在标红处,我们能发现el还是 {{message}},这里就是应用的 Virtual DOM(虚拟Dom)技术,先把坑占住了。到后面mounted挂载的时候再把值渲染进去。

clipboard.png

update 相关

这里我们在 chrome console里执行以下命令

app.message= 'yes !! I do';

下面就能看到data里的值被修改后,将会触发update的操作。

clipboard.png

destroy 相关

有关于销毁,暂时还不是很清楚。我们在console里执行下命令对 vue实例进行销毁。销毁完成后,我们再重新改变message的值,vue不再对此动作进行响应了。但是原先生成的dom元素还存在,可以这么理解,执行了destroy操作,后续就不再受vue控制了。

app.$destroy();

clipboard.png

生命周期总结

这么多钩子函数,我们怎么用呢,我想大家可能有这样的疑问吧,我也有,哈哈哈。

beforecreate : 举个栗子:可以在这加个loading事件 
created :在这结束loading,还做一些初始化,实现函数自执行 
mounted : 在这发起后端请求,拿回数据,配合路由钩子做一些事情
beforeDestroy: 你确认删除XX吗? destroyed :当前组件已被删除,清空相关内容
 
转载: https://www.jianshu.com/p/8314ccd03fa9
https://segmentfault.com/a/1190000008010666
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值