Reputation: 3557
I’m new to using Vue. I’m trying to wrap my head around plugins. What i’m stuck on is using a component and its method that I add to my plugin:
Component: Rest.vue
...
export default {
name: 'rest',
data () {
return {
}
},
methods: {
gplFetch: function(query){
...
return ...;
}
}
}
...
Plugin: global-plugin
import Rest from ‘@/components/Rest.vue’
export default {
install(Vue, options) {
Vue.component(Rest.name, Rest)
Vue.mixin({
created() {
console.log('rest created');
}
})
Vue.prototype.$gplFetch = function(query){
return <Access Rest component>.gplFetch(query);
}
}
}
Using in main.js
import GlobalPlugin from '@/plugins/global-plugin.js'
Vue.use(GlobalPlugin);
What i’m stuck on is how to access gplFetch in the code above:
return <Access Rest component>.gplFetch(query);
Upvotes: 1
Views: 570
Reputation: 82439
In order to make the code work the return should be
return Rest.methods.gplFetch(query);
But I would suggest taking a different approach and creating a module that contains the gplFetch
function (or perhaps an API module) and importing that method into both your plugin and the Rest.vue
component.
gplFetch.js
export function gplFetch(query){
// do something with query
}
Rest.vue
import {gplFetch} from "./gplFetch.js"
export default {
name: 'rest',
data () {
return {
}
},
methods: {
gplFetch
}
}
global-plugin.js
import {gplFetch} from "./gplFetch.js"
export default {
install(Vue, options) {
Vue.component(Rest.name, Rest)
Vue.mixin({
created() {
console.log('rest created');
}
})
Vue.prototype.$gplFetch = function(query){
return gplFetch(query);
}
}
}
This of course, all assumes that gplFetch
doesn't rely on any data in the Rest.vue
instance, because if it does it won't work from your plugin in the first place.
Upvotes: 1