【问题标题】:TypeError: Cannot read property '$http' of undefinedTypeError:无法读取未定义的属性“$http”
【发布时间】:2019-05-16 18:34:08
【问题描述】:

尝试使用 vue-resource 但我正在解决标题中描述的错误。下面的代码在名为 network.js 的 utils 部分中:

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
}

这就是它被调用的代码。它存在于我的一条名为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>

我正在按照他们在示例中描述的方式使用它,但我不确定我缺少什么?

【问题讨论】:

    标签: vue.js vuejs2 vue-resource


    【解决方案1】:
    • network.js 缺少对 Vue.use(VueResource) 的调用,如用于 Webpack 项目的 documented

      import Vue from 'vue'
      import VueResource from 'vue-resource'
      
      Vue.use(VueResource)
      
    • getConfig() 是一个箭头函数,它永久 绑定了一个词法this(调用者cannot rebind this),而thisundefinednetwork.js 的范围内。

      如果您打算让调用者(即组件)通过Function.prototype.call 将自己指定为上下文,则必须将getConfig 声明为常规函数:

      // 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

      另一种解决方案是使用mixins,这样您就可以调用this.getConfig()(不传递上下文):

      // 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多