how can component delete itself in Vue 2.0

Ciao picture Ciao · Nov 6, 2016 · Viewed 55k times · Source

as title, how can I do that

from offical documentation just tell us that $delete can use argument 'object' and 'key'

but I want delete a component by itself like this

this.$delete(this)

Answer

bendytree picture bendytree · Mar 27, 2019

I couldn't find instructions on completely removing a Vue instance, so here's what I wound up with:

module.exports = {
  ...
  methods: {
    close () {
      // destroy the vue listeners, etc
      this.$destroy();

      // remove the element from the DOM
      this.$el.parentNode.removeChild(this.$el);
    }
  }
};

Vue 3 is basically the same, but you'd use root from the context argument:

export default {
  setup(props, { root }){
    const close = () => {
      root.$destroy();
      root.$el.parentNode.removeChild(root.$el);
    };
    return { close };
  }
}

In both Vue 2 and Vue 3 you can use the instance you created:

const instance = new Vue({ ... });
...
instance.$destroy();
instance.$el.parentNode.removeChild(instance.$el);