在 main.js(对于 VueJS)中导入组件的利弊是什么? [英] What are the pros/cons of importing components in main.js (for VueJS)?

查看:42
本文介绍了在 main.js(对于 VueJS)中导入组件的利弊是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 vue-cli + webpack 作为我的开发环境,并且我在 main.js 中包含/声明了大多数组件为 Vue.component('<name>',require('./components/.vue'));

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

仅在需要的地方导入组件在开发/生产中是否有优势,或者像我现在所做的那样在 main.js 文件中执行此操作没有任何区别?

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?

推荐答案

我认为全局注册的主要好处是你的组件总是可用的,而不必在每个组件中注册它.如果您正在注册自己的自定义组件并且您知道不会有任何命名冲突,那么这很好.真正的问题是您是否正在编写可在多个项目中重复使用的组件.

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.

例如,我刚刚在 vue 中编写了一个星级评分应用程序,我计划在多个项目中使用它并通过 npm 发布,因此任何人都可以使用该组件在他们的项目中.主要组件本身需要另一个名为 star 的组件.如果我要全局注册 star,任何包含我的星级评定组件的项目现在都将在整个应用程序中都有一个名为star"的全局组件,但是,如果您已经注册了自己的组件命名星我们会遇到命名冲突,这意味着一个组件将覆盖另一个:

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/

当您根据需要注册组件时,可以避免任何命名冲突,因为注册的组件仅限于它们自己的范围.在以下示例中,两个组件都注册了一个名为message"的组件(并且都使用相同的模板),但每个组件都引用了不同的message"组件,因此它们输出不同的消息:

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/

这篇关于在 main.js(对于 VueJS)中导入组件的利弊是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆