Search code examples
vue.jscomponents

How to destroy vuejs component from outside of component


I have created one of component in vuejs something like this

    var tree_data = Vue.extend({
        template: '#tree_data_template',
        props: [
            'groupmodal',
            'search-name',
            'tree-id'
        ], // props in single quotes
        data: function () {
            return {
                shared: d2d.store
            };
        }
    });

And use this component in another template like this.

var template_data = Vue.extend({
template: '#template_data',
created: function () {
    var self = this;
    self.shared.setCurrentRoute('templates');
},
components: {
    'tree-data': tree_data
},
data: function () {
    return {
        id: this.$route.params.id,
        shared: d2d.store,
    };
},
methods: {
    destroyComponent: function () {
        //Need to code for destroy tree-data component
    }
}
});

Blade file code

<tree-data 
     groupmodal="false"                 
     search-name="user_search" 
     tree-id="user_tree" 
>
</tree-data>

So finally how can i destroy my "tree-data" component through the "destroyComponent()" method


Solution

  • As cobaltway said you can use v-if

    Setting v-if initially to false will render(generate) the component.

    Then in your method setting v-if to true will destroy the component.

    html

    <div id="template_data">
         <tree-data v-if="destroyComponent"></tree-data>
    </div>
    

    script

    var template_data = Vue.extend({
    template: '#template_data',
    created: function () {
        var self = this;
        self.shared.setCurrentRoute('templates');
    },
    components: {
        'tree-data': tree_data
    },
    data: function () {
        return {
            id: this.$route.params.id,
            shared: d2d.store,
            destroyComponent:true
        };
    },
    methods: {
        destroyComponent: function () {
            //Need to code for destroy tree-data component
            this.destroyComponent = false;
        }
    }
    }); 
    

    Here is the fiddle