Reputation: 969
I developed a plugin to centralize HTTP calls and need to access its function ($ap
i) from an imported module in a component.
The following works fine:
The plugin (http-transport.js)
export default {
install: function (Vue) { ...
Vue.prototype.$api = (...)
main.js
import HTTPTransport from './http-transport/http-transport'
Vue.use (HTTPTransport);
Usage from any component.vue
methods: {
someMethod() {
this.$api(...)
}}
All the above works.
Now, I have a SFC component that imports a module component.vue
import logic from "./LogicService.js";
The question: how can I call $api
from a function within LogicService.js
?
The real case is that LogicService.js imports DataService.js from which I need to call the $api function, but I guess the solution to the question solves this as well. Thanks so much! (vue 2.6.11)
Upvotes: 1
Views: 1045
Reputation: 878
there are couple ways to do that. the most easy way is just import vue and call the function. but for that case you must add the plugin function as global to vue
for example. in http-transport.js
export default function (Vue) {
//add global method or property
Vue.api= function () {
// some logic ...
api();
}
//add an instance method
Vue.prototype.$api= function () {
// some logic ...
api();
}
}
function api(){
//code goes here
}
and then in your js files just import Vue
and call Vue.api()
.
for example in LogicService.js
import Vue from "vue";
export default function(){
//call api
Vue.api();
}
the problem with this way is that you can access Vue.api
only when vue finish installize (most cases that the case so no problem).
a second way you can do that is to write the plugin like that
export default function (Vue) {
//add global method or property
Vue.api= function () {
// some logic ...
api();
}
//add an instance method
Vue.prototype.$api= function () {
// some logic ...
api();
}
}
export function api(){
//code goes here
}
now the plugin is actually indepent of vue and can work by itself without vue. for example now you can do that in LogicService.js
import {api} from './http-transport.js'
api()
Upvotes: 2