What are the pros/cons of importing components in

2019-07-15 06:25发布

I'm using vue-cli + webpack as my dev environment and I have most components included/declared in main.js as Vue.component('<name>',require('./components/<name>.vue'));

Is there an advantage in development/production to import components only where needed or it makes no difference to do it in the main.js file as I'm doing now?

标签: vue.js vuejs2
1条回答
The star\"
2楼-- · 2019-07-15 06:54

I think the main benefit of registering globally is that your component is always available without having to register it in every component. This is fine if you are registering your own custom components and you know that there won't be any naming collisions. The real problem is if you are writing components that may be reused across multiple projects.

As an example, I just wrote a star rating app in vue which I plan to use in multiple projects and have published via npm, so anybody can use the component in their project. The main component itself requires another component named star. If I were to register star globally, any project that includes my star rating component up will now have a global component named 'star' available throughout the entire app, however, if you have already registered your own component named star we get a naming collision, meaning one component will overwrite the other:

http://jsfiddle.net/krb23sq3/

When you register components as you need them, you avoid any naming collisions because the registered components are confined to their own scope. In the following example both components have a component named 'message' registered (and both are using the same template) but each one refers to a different 'message' component, so they output a different message:

http://jsfiddle.net/24hwu7at/

查看更多
登录 后发表回答