vuejs中的生命周期

vue中生命周期分为初始化,跟新状态,销毁三个阶段

1.初始化阶段:beforeCreated,created,beforeMount,mounted

2.跟新状态:beforeUpdate,update

3.销毁vue实例:beforeDestory,destoryed

其中created/mounted 可以用来发送ajax请求,启动定时器等异步任务

beforeDestroy用来收尾工作,如清除定时器

举个例子:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>09_Vue实例_生命周期</title>
</head>
<body>
<div id="test">
  <button @click="destroyVue">destory vue</button>
  <p v-if="isShow">你好</p>
</div>

<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
  new Vue({
    el: '#test',
    data: {
      isShow: true
    },

    beforeCreate() {
      console.log('beforeCreate()')
    },

    created() {
      console.log('created()')
    },

    beforeMount() {
      console.log('beforeMount()')
    },

    mounted () {
      console.log('mounted()')
      // 执行异步任务
      this.intervalId = setInterval(() => {
        console.log('-----')
        this.isShow = !this.isShow
      }, 1000)
    },


    beforeUpdate() {
      console.log('beforeUpdate()')
    },
    updated () {
      console.log('updated()')
    },


    beforeDestroy() {
      console.log('beforeDestroy()')
      // 执行收尾的工作
      clearInterval(this.intervalId)
    },

    destroyed() {
      console.log('destroyed()')
    },

    methods: {
      destroyVue () {
        this.$destroy()//触发 beforeDestroy 和 destroyed 的钩子。
      }
    }
  })


</script>
</body>
</html>

运行结果:

vuejs中的生命周期