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>

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM