首页 文章

Vue:多次创建相同组件时会发生什么

提问于
浏览
1

我'm a new with Vue. I'm有一个小的Vue应用程序,动态加载组件 . 每次我显示一个模块,我从服务器加载该模块的模板,javascript并运行它 . 在模块中,我通过Vue.component()创建一个Vue组件 . 因此,如果在之前创建了一个组件,那么当我重新创建它时会发生什么 .
Vue是否会缓存它并且不会重新创建新缓存或不缓存它?
如果Vue将其缓存在组件的构造函数中,我如何知道该组件已显示!

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

谢谢!

1 回答

  • 1

    我已经对它进行了测试,似乎它没有创建相同的命名组件,它只使用旧的组件 .

    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>
    

    我还发现Vue.options.components包含已定义的组件列表,因此您还可以将新组件名称与其可用键进行比较,并避免重新声明它 .

    Vue.options.components 的键值对请参见我们制作的最后一个组件 .

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

相关问题