this调用问题

var add = {
        template: "<div class='re-box'><div><span>姓名</span><input type='text' id='name' v-model='name'/></div>"+
            "<div><span>月份</span><input type='number' id='month' v-model='month'/></div>"+
            "<div><span>成交数</span><input type='number' id='dones' v-model='dones'/></div>"+
            "<div><span>成交量</span><input type='number' id='doneCount' v-model='doneCount'/></div>"+
            "<button id='add' @click='add'>提交</button></div>",
        data:function() {
            return {
                name:"",
                month:null,
                dones:null,
                doneCount:null
            }
        },
        methods:{
            add:function() {
                if(this.name == "" || this.month == null || dones == null || doneCount == null) {
                    alert("内容不能为空");
                    return;
                }
                Vue.http.post(baseUrl+"/add/"+this.name+"/"+this.month+"/"+this.dones+"/"+this.doneCount).then(function(res){
                    var mes = res.body;
                    if(mes == "exist") {
                        alert("数据已存在");
                    } else if(mes == "success") {
                        alert("提交成功");
                        alert(this.name);
                    }
                },function(res){
                    console.log(res.status);
                });
            }
        }
    };

then方法以外的this调用正常,为什么then里面的this调用就不对呢?

阅读 1.4k
1 个回答

用箭头函数,或者在http请求外面,建个对象指向this然后在then里使用

Vue.http.post(baseUrl+"/add/"+this.name+"/"+this.month+"/"+this.dones+"/"+this.doneCount).then((res) => {
    var mes = res.body;
    if(mes == "exist") {
        alert("数据已存在");
    } else if(mes == "success") {
        alert("提交成功");
        alert(this.name);
    }
},function(res){
    console.log(res.status);
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题