【问题标题】:Data not updating in Vue数据未在 Vue 中更新
【发布时间】:2016-03-23 13:23:35
【问题描述】:

当我触发该方法时,我得到了我想要的字符串,但不确定为什么它没有保存在数据对象上。任何帮助将不胜感激。谢谢

new Vue({
  el: '#app',
  data: {
    output: '' // <- var test (string) 
  },
  methods: {
    searchProperty: function () {
        $.get(baseUrl, function(res) {
            var test = $(res).find('#label_bin_output').text();
            this.output = test;
        });
    }
  }
});

更新:忘了提到我正在使用 jQuery 进行 ajax 请求。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:
    new Vue({
      el: '#app',
      data: {
        output: '' // <- var test (string) 
      },
      methods: {
        searchProperty: function () {
            var self = this;
            ^^^^^^^^^^^^^^^^
            $.get(baseUrl, function(res) {
                var test = $(res).find('#label_bin_output').text();
                self.output = test;
                ^^^^
            });
        }
      }
    });
    

    【讨论】:

      【解决方案2】:

      问题是“this.output”在 Jquery 的范围内; (这个 == jquery)。

      你需要引用 main obj:

      new Vue({
         el: '#app',
         data: {
           output: '' // <- var test (string) 
         },
         methods: {
          searchProperty: function () {
              var _self = this; // ref to main...
              $.get(baseUrl, function(res) {
                  // try console.log this and _self
                  console.log(_self);
                  console.log(this);
                  var test = $(res).find('#label_bin_output').text();
                  _self.output = test;
              });
          }
        }
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 2021-11-06
        • 2018-08-31
        • 1970-01-01
        • 2017-12-03
        • 1970-01-01
        • 2019-12-06
        相关资源
        最近更新 更多