Vikram Anand Bhushan
Vikram Anand Bhushan

Reputation: 4886

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

I have following code

<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);
          })
      }
  }
});

When I run the above code it gives me following error

Uncaught TypeError: Cannot read property 'get' of undefined

I have a fiddle

JsFiddle

Help would be much appreciated

Upvotes: 2

Views: 18502

Answers (5)

RajKon
RajKon

Reputation: 470

I used another way as of Oct 2019. I first installed using NPM like this

npm install axios --save

I used this below later and doing this below got rid of the error.

import  axios  from 'axios';

Upvotes: 0

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 11

I fixed this issue of the following mode:

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

in main.js

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

Vue.use(BootstrapVue)

create bootstrap.js

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

Vue.use(VueResource)

export { Vue }

In App.vue

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

Upvotes: 0

Subham Mitra
Subham Mitra

Reputation: 41

In order to use $http you must install the vue-resource middleware first. You can use the following command to install it.

npm install vue-resource --save

After its installed go to your main.js file and import the vue resource as follows

import vueResource from 'vue-resource'

Now its imported so we just have to call the use method of Vue to work with this middleware. You can call the use method as follows.

Vue.use(vueResource)

Upvotes: 4

Saurabh
Saurabh

Reputation: 73609

$http.get is from Vue Resource. Make sure you are pulling that in properly by adding vue-resource to your package.json, install it via npm install and in code:

var Vue = require('vue');

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

To use this in fiddle, you have to add vue-resource cdn link in external resources and use following in code:

Vue.use(VueResource)

See working demo: https://jsfiddle.net/49gptnad/187/

Upvotes: 6

Amresh Venugopal
Amresh Venugopal

Reputation: 9549

As you have no plugin for vue-resource your this.$http is undefined. To add Vue-resource on js-fiddle add https://cdn.jsdelivr.net/g/[email protected],[email protected] to the external scripts section.

Upvotes: 0

Related Questions