【问题标题】:Vue: What happens when create a same component many timesVue:多次创建同一个组件时会发生什么
【发布时间】:2018-06-03 17:36:36
【问题描述】:

我是 Vue 的新手。我有一个动态加载组件的小型 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;
        }
    }
});

谢谢!

【问题讨论】:

    标签: vue.js vue-component


    【解决方案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 具有已定义的组件列表,因此您还可以将新组件name 与其可用的keys 进行比较,并避免重新声明它。

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

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

    【讨论】:

    • 谢谢!我明白了,Vue.options.components 很有帮助
    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 2017-09-07
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多