简体   繁体   中英

Does Vue can import component by dependency inject(DI) like angular?

I used angularjs(1.x) and new to Vue.There has DI in angular and refer a service in controller or a directive in template is easy, wherever the service or directive is. Angular will help you inject it automatically.

But I realize Vue refer a component by import(ES6) the path where the component in.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.

I know there have a vue-injector like angular DI, but if it is easy to use?

If you think you are going to restructure a lot, you can have one file that everyone imports and it imports all the rest, that way you only need to change in one place.

I personally prefer the import over the Dependency Injection, way easier to understand where everything is coming from.

Vue doesn't provide any formal dependency injection mechanism. It's completely up to you how you want to import dependencies.

Most Vue code samples do not use dependency injection at all and just use the ES6 module system via import and export .

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.

You probably shouldn't be changing the directory structure frequently. Check out the Vue webpack template for an example of how to correctly structure a Vue project.

That being said, it doesn't really answer your question. Are you using webpack (or something similar)? You can configure precisely how webpack should locate modules via the resolve configuration property, so that you don't have to use relative import paths.

Another way is to register each Vue component globally so you don't need to import them at all.

Another way is to abuse ES6 modules by creating, say, a components.js module which imports each Vue component (wherever they are) and exports them all from that one module. Now you only need to import from that central module instead of hunting down the specific module location of each thing you want to import.

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

If you change the location of button.vue , you only need to update the import from inside the components.js file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM