how can component delete itself in Vue 2.0

后端 未结 4 1005
有刺的猬
有刺的猬 2021-01-03 18:47

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 its

相关标签:
4条回答
  • 2021-01-03 19:13

    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)
    },
    
    0 讨论(0)
  • 2021-01-03 19:17

    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

    0 讨论(0)
  • 2021-01-03 19:30

    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.

    0 讨论(0)
  • 2021-01-03 19:34

    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);
    
    0 讨论(0)
提交回复
热议问题