【问题标题】:How to retrieve data in nodejs from post api with vuejs如何使用 vuejs 从 post api 中检索 nodejs 中的数据
【发布时间】:2017-08-21 10:44:55
【问题描述】:

我正在尝试在 nodejs 中编写一个 post api 并使用 vuejs 作为前端框架并使用 vue-resource 来访问 apis 。这是我在前端的提交功能。

validateBeforeSubmit() {
        var self = this;

        this.$validator.validateAll().then(result => {
          if (result) {
            self.data = self.name;
            console.log(this.data)
            this.$http.post('/api/add_level',self.data).then(function(res){
              this.status = res.body
              console.log(this.status);
            this.largeModal=false;
            // eslint-disable-next-line
            alert('From Submitted!');


            })
            return;

          }

这是我在服务器端的代码。

app.post('/api/add_level',function(req,res,err,data){
    console.log(data);
})

【问题讨论】:

    标签: node.js api post vue.js


    【解决方案1】:

    你有一个变量 var self = this 指向正确的 vue instancre ,那么你为什么在你回调 vue-resource 的 post 请求时再次使用 this

    在方法中的任何时候都使用self 来引用vue 实例。由于closures 的概念,这是可能的。

    所以把你的代码改成:

        this.$validator.validateAll().then(function(result) {
          if (result) {
            self.data = self.name;
            console.log(this.data)
            this.$http.post('/api/add_level',self.data).then(function(res){
              self.status = res.body
              console.log(self.status);
            self.largeModal=false;
            // eslint-disable-next-line
            alert('From Submitted!');
    
    
            })
            return;
    
          }
    

    注意

    我建议您使用普通函数语法并使用闭包或使用arrow function,因为它们在词法上绑定this。不要混合使用并同时使用

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 2017-12-26
      • 1970-01-01
      • 2018-01-09
      • 2014-11-15
      • 2012-12-01
      • 2021-02-08
      • 2018-02-12
      • 1970-01-01
      相关资源
      最近更新 更多