Uncaught TypeError: Cannot read property 'get' of undefined in VueJs

Uncaught TypeError: Cannot read property 'get' of undefined in VueJs

我有以下代码

<div id="vue-instance">

</div>

JS

var vm = new Vue({
  el: '#vue-instance',
  data: {
  },
  ready:function(){
    this.loadCountries();
  },
  methods:{
        loadCountries(){
            this.$http.get('https://restcountries.eu/rest/v1/all',function(data){
                console.log(data);
          })
      }
  }
});

当我运行上面的代码时,它给了我以下错误

Uncaught TypeError: Cannot read property 'get' of undefined

我有一个fiddle

JsFiddle

帮助将不胜感激

$http.get 来自 Vue Resource。确保通过将 vue-resource 添加到 package.json 来正确地引入它,通过 npm install 和代码安装它:

var Vue = require('vue');

Vue.use(require('vue-resource'));

要在 fiddle 中使用它,您必须在外部资源中添加 vue-resource cdn link 并在代码中使用以下内容:

Vue.use(VueResource)

查看工作演示:https://jsfiddle.net/49gptnad/187/

因为你没有 vue-resource 插件,你的 this.$http 是未定义的。 要在 js-fiddle 上添加 Vue-resource,请将 https://cdn.jsdelivr.net/g/vue@2.0.0-rc.4,vue.resource@1.0.0 添加到外部脚本部分。

为了使用 $http 你必须先安装 vue-resource 中间件。您可以使用以下命令安装它。

npm install vue-resource --save

安装后转到您的 main.js 文件并导入 vue 资源,如下所示

import vueResource from 'vue-resource'

现在它已导入,因此我们只需调用 Vueuse 方法即可使用此中间件。您可以调用 use 方法,如下所示。

Vue.use(vueResource)

我修复了以下模式的这个问题:

npm install bootstrap-vue --save
npm install vue-resource --save

在 main.js

import Vue from './bootstrap'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)

创建bootstrap.js

import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

export { Vue }

在App.vue

this.$http.get('/api/module/all').then(...

自 2019 年 10 月起,我使用了另一种方式。我首先使用 NPM 安装是这样的

npm install axios --save

我后来在下面使用了这个并且在下面这样做摆脱了错误。

import  axios  from 'axios';