Issue
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?
Solution
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.
Answered By - Decade Moon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.