TypeError: Cannot read property '$http' of undefined

人盡茶涼 提交于 2021-02-10 18:48:42

问题


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?


回答1:


  • 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



来源:https://stackoverflow.com/questions/53797498/typeerror-cannot-read-property-http-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!