【问题标题】:this.$http.get seems doesn't work vue-resourcethis.$http.get 似乎不起作用 vue-resource
【发布时间】:2017-12-16 10:44:56
【问题描述】:

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

但最终

用户没有价值。

【问题讨论】:

  • Vue.set 的参数是 (target, key, value)。见vuejs.org/v2/api/#Vue-set
  • 试试this.users = data
  • 我试过 this.users = data ,,, 不起作用! :| :(
  • 您的 .../api/api/.. 网址似乎可疑
  • 网址正常工作

标签: javascript vue.js vuejs2 vue-resource


【解决方案1】:
     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()
        }
    });

检查变量范围。像“self”一样设置指向“this”的指针。

【讨论】:

    【解决方案2】:

    Vue-resource 是一个基于 Promise 的 API。 获取请求的语法应该是

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

    由于你已经在data选项中初始化了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 
            })
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2019-03-07
      • 2016-11-29
      • 2016-02-01
      • 2020-09-23
      相关资源
      最近更新 更多