1

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);

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. You gave a solution, but you also offered a better solution that I decided to take. You are awesome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.