Search code examples
javascriptvue.jsvuejs2vue-resource

this.$http.get seems doesn't work vue-resource


uses vue 2.1.10 vue-resource 1.3.4 to fetch the data:

    const app = new Vue({
    el: '#UserController',
    data:{
      users : [],
    },
    methods:{
      fetchUser: function(){
          this.$http.get('http://localhost:8000/api/api/users', function(data){
              this.$set('users',data)
          })
      }
    },
    mounted(){
        this.fetchUser()
    }
});

but in the end

users has no value.


Solution

  • Vue-resource is a promise based API. The syntax for the get request should be

    this.$http.get('/someUrl')
        .then(response => { 
            // get body data
            this.someData = response.body; 
        }, err => { 
            // error callback 
        }); 
    

    Since you have initialized users: [ ] in the data option , no need to use Vue.$set you can directly assign the value using this.users = data

    So do it like this:

    fetchUser: function(){
          this.$http.get('http://localhost:8000/api/api/users')
            .then((data) => {
                this.users = data;
            }, err => {
                // handle error 
            })
    }