this.$http.get, кажется, не работает vue-resource

Использует vue 2.1.10 vue-resource 1.3.4 для извлечения данных:

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

но в конце

пользователи не имеют значения.

2 ответа

Решение

Vue-ресурс - это API, основанный на обещаниях. Синтаксис запроса get должен быть

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

Так как вы инициализировали users: [ ] в опции данных, нет необходимости использовать Vue.$set Вы можете напрямую присвоить значение, используя this.users = data

Так что сделайте это так:

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

Проверьте переменную область. Установите указатель на "это", как "я".

Другие вопросы по тегам