Lifecycle Events of Vue Component

Lifecycle Events of Vue Component demo by http://qcode.in

by Saqueib Ansari

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div class="container">
  <div id="app">
    <div class="text-center" v-if="!showPanel">
      <button @click="$root.showPanel = !$root.showPanel">Created Component Panel
      </button>
    </div>
    <bs-panel v-if="showPanel"></bs-panel>
    
    <p class="text-warning text-center">Open the Dev Console to see hooks calls</p>
  </div>
</div>


<!-- Templates -->
<template id="panel">
  <div class="panel panel-default">
    <div class="panel-heading">Vue Lifecycle Hooks</div>
    <div class="panel-body">
      <div class="row">
        <div class="col-xs-6">
          <p class="text-info">Trigger Update event</p>

          <p>Count <span class="text-success">{{ count }}</span></p>
          <button @click="count++">+</button>
          <button @click="count--">-</button>
        </div>
        <div class="col-xs-6">
          <p class="text-info">Trigger destroy event</p>
          <button @click="$root.showPanel = !$root.showPanel">Destroy</button>
        </div>
      </div>

    </div>
  </div>
</template>

CSS

body {
  margin-top: 1rem
}

JavaScript

// Component 
Vue.component('bs-panel', {
  template: '#panel',
  data: function() {
    return {
      count: 0
    }
  },

  beforeCreate: function() {
    console.log('beforeCreate fired');
  },
  created: function() {
    console.info('created fired');
  },
  beforeMount: function() {
    console.log('beforeMount fired');
  },
  mounted: function() {
    console.info('mounted fired');
  },
  beforeUpdate: function() {
    console.log('beforeUpdate fired');
  },
  updated: function() {
    console.info('updated fired');
  },
  beforeDestroy: function() {
    console.log('beforeDestroy fired');
  },
  destroyed: function() {
    console.info('destroyed fired');
  }
});

// Initialize Vue
new Vue({
  el: '#app',
  data: {
    showPanel: true
  }
})