vue.jsvuejs2vue-resource

Unable to access `get` method in vue-resource


I have a tiny vue app where I'm wanting to use vue-resource to request an api endpoint.

  1. I've installed vue-resource via npm
  2. I've added the Vue.use(VueResource) lines to my bootstrap file
  3. I've setup my component like this to call the .get method

Blog.vue

...
mounted () {
  this.fetchPosts()
},
methods: {
  fetchPosts: () => {
    debugger;
    this.$http.get('my-url')
      .then(response => {
        console.log(response)
      })
  }
}
...

I've seen a few github issues and SO posts which touch on this type of problem but most seem to relate to incorrect configuration which I don't think I have (happy to be proven wrong!)

The specific console error I get is:

Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"

What's odd about this is that if you see my debugger line, if I console.log this.$http.get at that point I get:

function (url, options$$1) {
        return this(assign(options$$1 || {}, {url: url, method: method$$1}));
    }

If I let the code run and then attempt the console.log afterwards I get:

Cannot read property 'get' of undefined

As a result I presume it's some kind of this context issue, but from what I can see the reference should be correct...shouldn't it?


Solution

  • Methods should not be arrows function. The this will not point to the vue instance if a methods is declared using arrow function.

    Use normal function instead:

    methods: {
      fetchPosts(){
        debugger;
        this.$http.get('my-url')
          .then(response => {
            console.log(response)
          })
      } 
    

    You can see the warning here