1
votes

I'm a new with Vue. I'm having a small Vue app that load components dynamically. Each time I show a module, I load template, javascript of this module from server and run it. In the module I create a Vue component by Vue.component(). So if a component has been created before then what happens when I re-create it.
Will Vue cache it and doesn't re-create a new one or not cache it?
If Vue cache it then in the component's constructor, how do I know that component is showed!

Vue.component("component", {
    template: '#component',
    data: function() {
        return {
            items: [],
            total: 0,
            page: 1,
            limit: 20
        }
    },
    created() {
        index.setExtensionCallback = function(params) {
            list(params);
        };
        sendListRequest({requestParams: {p: 1, np: this.limit}});
    },
    methods: {
        sendListRequest: function(params) {
            var listingCmd = 21;
            index.chanadmin.extensionRequest({cmd: listingCmd, requestParams: params.requestParams});
        },
        list: function(params) {
            this.items = params.ar;
            this.total = params.total;
        }
    }
});

Thanks!

1

1 Answers

2
votes

I have tested it and seems its not creating same named component again it uses that old one only.

Vue.component("comp", {
    template: '#component',
    data: function() {
        return {
            msg: 'first declared compo.',            
        }
    },    
    created: function() {
      console.log('comp 1');
    }
});

// mimicking ajax
setTimeout(function() {
  console.log('Ajax Call Knok! knok! 2')
  Vue.component("comp", {
    template: '#component',
    data: function() {
        return {
            msg: 'second declared after 2 second declared compo.',
        }
    },
    created: function() {
      console.log('comp 2');
    }
  });
}, 2000);

// console.log(Vue.options.components);  
 var vm = new Vue({
    el: '#app',
    data: {   
        msg: 'Main Instance'
    }    
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    <div id="app">
        {{ msg }}
        <comp></comp>        
    </div>
  
  <script type="text/x-template" id="component">
    <h3>{{ msg }}</h3>
  </script>

</body>

</html>

I also found that Vue.options.components has list of components which are defined so you can also compare new component name with its available keys and avoid to re-declare it.

key value pair for Vue.options.components see last component which we have made.

KeepAlive: Object
Transition: Object
TransitionGroup: Object
comp: VueComponent(options)