我使用了 angularjs(1.x),并且是 Vue 的新手。有 DI
在 Angular 中,无论服务或指令在哪里,引用 Controller 中的服务或模板中的指令都很容易。 Angular 会帮你自动注入(inject)。
但我意识到 Vue 通过 import(ES6)
引用组件组件所在的路径。如果我在重构时(经常)更改组件目录结构,就会丢失组件引用,我应该一一修复路径。多麻烦啊。
我知道有一个vue-injector
类似于 Angular DI,但它是否易于使用?
最佳答案
Vue 不提供任何正式的依赖注入(inject)机制。如何导入依赖项完全取决于您。
大多数 Vue 代码示例根本不使用依赖注入(inject),只是通过 import
和 export
使用 ES6 模块系统。
If I change the component direcotry structure when refactoring(frequently), there will lost the component refer, and I should fix the path one by one. How troublesome it is.
您可能不应该经常更改目录结构。查看Vue webpack template有关如何正确构建 Vue 项目的示例。
话虽如此,它并没有真正回答你的问题。你正在使用 webpack (或类似的东西)吗?您可以通过 resolve 精确配置 webpack 如何定位模块。配置属性,这样您就不必使用相对导入路径。
另一种方法是register each Vue component globally所以你根本不需要导入它们。
另一种方法是滥用 ES6 模块,例如创建一个 components.js
模块,该模块导入每个 Vue 组件(无论它们在哪里)并从该模块导出所有组件。现在,您只需要从该中央模块导入,而不是寻找要导入的每个内容的特定模块位置。
// components.js
import Button from 'path/to/button.vue';
import Alert from 'path/to/alert.vue';
export {
Button,
Alert,
};
// myform.js
import { Button } from 'path/to/components.js';
如果更改 button.vue
的位置,则只需更新 components.js
文件内部的导入即可。
关于angularjs - Vue 可以像 Angular 一样通过依赖注入(inject)(DI)导入组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44616174/