Destroying a Vue instance

Published on April 27, 2017 by

In this short post, I want to show you how you can destroy a Vue instance. Usually you won’t need to do this yourself, though. When we get into talking about components, we will see that it is better to control the lifecycle of child components by using directives such as the v-if directive. That’s for a future post, though, but I just want you to know that you typically won’t need to worry about manually destroying Vue instances. So unless there is a good reason for you to do this, then you don’t have to worry about it. Nevertheless, I am going to show you how to do it in case you will need it.

<div id="app">
  <h1>Counter: {{ counter }}</h1>
  <button @click="counter++">Increase Counter</button>
</div>
var vm = new Vue({
	el: '#app',
	data: {
		counter: 1
	}
});

So I have a Vue instance with a counter data property and a button which increases the number stored within this property. After five seconds, I want to destroy the Vue instance just so we can see that the button stops responding to the click event.

setTimeout(function() {
	vm.$destroy();
}, 5000);

If you start clicking the button, you will see that the counter stops increasing after five seconds. At this point, the Vue instance has been completely destroyed.

Notice that while the Vue instance is now gone, the DOM is left as is. So the DOM will be left as it was at the point of destroying the Vue instance.

That’s all it takes to destroy a Vue instance. No more, no less.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

Here is what you will learn:

  • How to build advanced Vue.js applications (including SPA)
  • How Vue.js works under the hood
  • Communicating with services through HTTP
  • Managing state of large applications with Vuex
  • ... and much more!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.