1

Trying to use vue-resource but i am etting the error described in the title. The code below is in utils section called network.js:

import VueResource from 'vue-resource'

const getConfig = () =>{
  console.log('its working');
  // GET /someUrl
  this.$http.get('https://fdsdfsdf-685a-45ed-8665-9847e0dbce0d.mock.pstmn.io/getConfig')
  .then(response => {

    // get body data
    this.config = response.body;

   }, response => {
     // error callback
   });
};

//Export login so other classes can use it
export{
  getConfig
}

And this the code where it gets called. It exists in one of my routes called Admin.vue:

<template>
  <div class="admin">
    <h1>This is admin page area</h1>
    <p>This is the data: {{this.config}}</p>
  </div>
</template>

<script>

import{getConfig} from "../utils/network";

export default{

  data: function () {
    return {
      config: [{}]
    }
  },
  created:function(){
      getConfig();
    }
}
</script>

I am using it as they describe in the example i am not really sure what i am missing?

0

1 Answer 1

2
  • network.js is missing a call to Vue.use(VueResource), as documented for Webpack projects:

     import Vue from 'vue'
     import VueResource from 'vue-resource'
    
     Vue.use(VueResource)
    
  • And getConfig() is an arrow function, which permanently binds a lexical this (callers cannot rebind this), and this is undefined in the scope of network.js.

    If you intended for callers (i.e., the components) to specify itself as the context via Function.prototype.call, you'd have to declare getConfig as a regular function:

     // network.js
     const getConfig = function() { ... }  // option 1
     function getConfig() { ... }          // option 2
    
     // MyComponent.vue > script
     import { getConfig } from '../utils/network.js'
    
     export default {
       created() {
         getConfig.call(this)
       }
     }
    

demo

Another solution is to use mixins so that you could call this.getConfig() (without passing the context):

    // network.js
    const getConfig = function() { ... }  // option 1
    function getConfig() { ... }          // option 2

    const getConfigMixin = {
      methods: {
        getConfig
      }
    };

    export { getConfigMixin }

    // MyComponent.vue > script
    import { getConfigMixin } from '../utils/network.js'

    export default {
      mixins: [getConfigMixin],
      created() {
        this.getConfig()
      }
    }

demo

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

Comments

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.