生命周期也叫钩子。

我在官网找了一张图,千万不要觉得这张图好复杂就不去认真的分析了,反而去看别人写的博客,反而越整越懵。

就下面这张图,为大家详解生命周期,然后贴出实例代码。

\"\"

生命周期说白了就是一套流程,而这套流程里面的方法就会有先后顺序的执行(调用了就执行,不调用就不会执行),整个流程分为三个步骤。

请看下图:

\"\"

第一个部分: 初始化显示

new Vue() 表示创建一个Vue实例,这里假设vm是新建的实例。

按照图上的流程是:beforeCreate() ➡ created() ➡ beforeMount() ➡ mounted()

第二个部分: 更新状态

beforeUpdate() ➡ updated()

第三个部分: 销毁Vue实例

vm.$destory()

beforeDestory() ➡ destoryed()

beforeDestory(): 做收尾工作(就是在结束之前做一些事情,如: 清除定时器)。

常用的生命周期方法

mounted,初始化之后就会立即调用。

created()/mounted():发送ajax请求, 启动定时器等异步任务。

实例代码

打开浏览器的开发者然后调试工具分析代码。

<!DOCTYPE html>
<html lang=\"en\">
<head>
  <  charset=\"UTF-8\">
  < >生命周期</ >
</head>
<body>

<div id=\"test\">
  <button @click=\"destroyVue\">destory Vue</button>
  <p v-if=\"isShow\">Hello,World</p>
</div>

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

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

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

    methods: {
      destroyVue () {
        this.$destroy()
      }
    }
  })

</ >
</body>
</html>

完整生命周期实例

<!DOCTYPE html>
<html lang=\"en\">
<head>
  <  charset=\"UTF-8\">
  < >生命周期</ >
</head>
<body>

<div id=\"test\">
  <button @click=\"destroyVue\">destory vue</button>
  <p v-if=\"isShow\">Hello,world!</p>
</div>

<  type=\"text/ \" src=\"../js/vue.js\"></ >
<  type=\"text/ \">
  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()
      }
    }
  })


</ >
</body>
</html>

生命周期的原理的话,经得起折腾的朋友去了解一下吧~

感谢您的阅读!

收藏 打印