Ciao
Ciao

Reputation: 637

how can component delete itself in Vue 2.0

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)

Upvotes: 52

Views: 115700

Answers (4)

HastingsDirect
HastingsDirect

Reputation: 668

You could use the beforeDestroy method on the component and make it remove itself from the DOM.

beforeDestroy () {
  this.$root.$el.parentNode.removeChild(this.$root.$el)
},

Upvotes: 8

Mani Jagadeesan
Mani Jagadeesan

Reputation: 24275

No, you will not be able to delete a component directly. The parent component will have to use v-if to remove the child component from the DOM.

Ref: https://v2.vuejs.org/v2/api/#v-if

Quoted from docs:

Conditionally render the element based on the truthy-ness of the expression value. The element and its contained directives / components are destroyed and re-constructed during toggles.

If the child component is created as part of some data object on parent, you will have to send an event to parent via $emit, modify (or remove) the data and the child component will go away on its own. There was another question on this recently: Delete a Vue child component

Upvotes: 44

Valentine Shi
Valentine Shi

Reputation: 7878

If you just need to re-render the component entirely you could bind a changing key value to the component <MyComponent v-bind:key="some.changing.falue.from.a.viewmodel"/>

So as the key value changes Vue will destroy and re-render your component.

Taken from here

Upvotes: 1

bendytree
bendytree

Reputation: 13647

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);

Upvotes: 71

Related Questions