實例解析vue生命週期

本篇文章重點講述vue組件的生命週期,主要形式是經過實例說明組件由創造到結束的過程。

vue組件週期

  1. beforeCreate
  2. created
  3. beforeMounte
  4. mounted
  5. beforeUpdate
  6. Updated
  7. beforeDestory
  8. destoryed

  生命週期的主要方法就是這些(詳細的講解請參考這篇文章),咱們經常使用的是mounted和beforeDestory這兩個方法,mounted方法是指組件的初始化工做都已經完成了,運行到這個階段,就能夠獲取到this中的數據和方法,而且能夠對dom進行操做,咱們一般是在該方法中進行ajax請求,定時器及其餘的異步操做;而在beforeDestory階段,若是有定時器,咱們會在這個方法中取消定時器。vue

實例解析

  下面咱們就用例子將整個流程走一遍:ajax

<body>
    <div id="app">
        <button @click="stop">中止閃爍</button>
        <p v-show="isshow">生命週期練習</p>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                isshow: true,
                interval: null
            },
            beforeCreate(){
                //在這個階段的特色是組件中的數據和方法獲取不到
                console.log('beforeCreate')
                console.log(this.isshow)
            },
            created(){
                console.log('created')
            },
            beforeMount(){
                console.log('beforeMount')
            },
            mounted(){
                console.log('mounted')
                this.interval = setInterval(()=>{
                    this.isshow = !this.isshow
                },1000)
            },
            beforeUpdate(){
                console.log('beforeUpdate')
            },
            updated(){
                console.log('updated')
            },
            beforeDestroy(){
                console.log('beforeDestroy')
                clearInterval(this.interval)
            },
            destroyed(){
                console.log('destroyed')
            },
            methods: {
                stop(){
                    this.$destroy()
                }
            }

        })
    </script>
</body>

  該例子想展現的效果是,文本內容每隔1s閃現一次,點擊上方按鈕可中止閃爍,在控制檯中會將組件從建立到銷燬整個過程打印出來。app

圖片描述

clipboard.png

  根據上面的例子,咱們能夠知道,在vue的生命週期中,只有與組件更新有關的方法會執行屢次,建立方法,掛載方法以及卸載方法都是隻會執行一次。dom