how can component delete itself in Vue 2.0

久未见 提交于 2020-08-19 05:56:33

问题


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)

回答1:


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://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




回答2:


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



回答3:


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)
},



回答4:


Instead of deleting your component from its parent you can still use v-if on the first <div> tag from the component itself. This would leave an empty component in your page and it's not best practice but may avoid handling events from parent.



来源:https://stackoverflow.com/questions/40445125/how-can-component-delete-itself-in-vue-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!