Vue Lifecycle Hooks tip

today we are going to talk about how to vue lifecycle hooks work programmatically. in this scenario i’m using vue cdn version.

following code snippet use for the example in this time. but you can use vue-cli also.

<!DOCTYPE html>
<html>
<head>
	<title>Vue life cycle Hooks</title>
</head>
<body>
	<div id="app"></div>
</body>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script type="text/javascript">
	new Vue({
	el:"#app",
		data() {
		return {
			 title:"Vue LifeCycle Hooks"
			}
		}
	})
</script>
</html>

created

created() hook is triggered when the vue instance is created. following example you can see the console it will triggered.

new Vue({
 el:"#app",
 created() {
  console.log('created instance');
 },
 data() {
 return {
   title:"Vue LifeCycle Hooks"
  }
 }
})

now its cool thing is we can use that as programmatically using $once(). its really amazing in vue lifecycle.

new Vue({
 el:"#app",
 created() {
 console.log('created instance');
 this.$once('hook:mounted', () => {
 console.log('mounted vue instance');
 })
},
data() {
 return {
 title:"Vue LifeCycle Hooks"
 }
}
})

There are also other hooks which will be called at different stages of the instance’s lifecycle, such as mounted, updated, and destroyed.

now let we see how this use for a actual vue component. for thisi’m creating new vue component as tryndev-component

Vue.component('tryndevComponent',{
template:`<div>
            <h2>My New component for Hooks</h2>
          </div>`
})

now we are going to do same thing in another way to our newly created component as follows

<tryndev-component
  @hook:mounted="itWasMounted"
  @hook:created="itWasCreated">
</tryndev-component>

Vue.component('tryndevComponent',{
template:`<div>
            <h2>My New component for Hooks</h2>
         </div>`
})
new Vue({
 el:"#app",
 data() {
 return {
 title:"Vue LifeCycle Hooks"
 }
},
methods: {
 itWasMounted() {
 console.log('It was mounted another way');
},
itWasCreated() {
  console.log('It was created in another way');
  }
 }
})

4 1 vote
Article Rating

by kushan


Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
shanika
shanika
3 years ago

vuex intergration tutor please