Home

May 8, 2017, 2 min read

Force reset a Vue Component

In Vue 2.0, resetting a Component would usually mean to reset its internal state. While it is suggested to do this using nested data properties that we can simply assign, we can also use a small hack to completely replace the Component's $data object like so: https://github.com/vuejs/vue/issues/702 Great, but that is not always enough. What if my component is wrapping a 3rd party library that does all kinds of funky things to the DOM that will not be reset by that? I have found another hack to "reset" a Component, that worked for my particular use case. It is quite brute force and relying on garbage collection, so probably not a great way to do it, but hey, you can give it a try anyways. Make sure to add your Component to the DOM conditionally:

<my-component v-if="drawComponent"></my-component>

Then to "reset", remove it from the DOM for one drawing cycle, which will destroy the Vue instance (which the Component ultimately is) and its state with it and then recreate it:

methods: {
  reset: function() {
    var vm = this;
    vm.drawComponent = false;
    Vue.nextTick(function() {
      vm.drawComponent = true;
    });
  }
}

EDIT: It seems we can also trigger a redraw of a component using the :key property: https://vuejs.org/v2/api/#key

guilty

After the implementation, guilty written all over his face.