首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >this.$http.get似乎不能工作vue-resource

this.$http.get似乎不能工作vue-resource
EN

Stack Overflow用户
提问于 2017-07-12 14:47:02
回答 2查看 910关注 0票数 0

使用vue 2.1.10 vue-resource 1.3.4来获取数据:

代码语言:javascript
复制
    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()
    }
});

但最终

用户没有价值。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-12 16:49:41

Vue-resource是一个基于promise的API。get请求的语法应为

代码语言:javascript
复制
this.$http.get('/someUrl')
    .then(response => { 
        // get body data
        this.someData = response.body; 
    }, err => { 
        // error callback 
    }); 

由于已在data选项中初始化了users: [ ],因此无需使用Vue.$set即可使用this.users = data直接赋值

所以你可以这样做:

代码语言:javascript
复制
fetchUser: function(){
      this.$http.get('http://localhost:8000/api/api/users')
        .then((data) => {
            this.users = data;
        }, err => {
            // handle error 
        })
}
票数 4
EN

Stack Overflow用户

发布于 2017-07-12 15:13:47

代码语言:javascript
复制
     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”。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45050331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档