【问题标题】:Computed method don't recognize updated data计算方法无法识别更新的数据
【发布时间】:2018-07-03 12:37:58
【问题描述】:

我正在尝试使用计算方法total 这计算字数并乘以priceprice 是通过访问 API 的方法获得的。 但是计算方法不使用更新的数据price。它返回空。

var app = new Vue({
  el: '#app',
  data: {
    text: '',
    qualidade: '',
    selected: '',
    options: [],
    lang1: '',
    lang2: '',
    ola: '',
    price: ''
  },
  beforeCreate: function() {
      axios.get('/languages.json')
        .then((response) => {
            this.options = response.data
        })
  },
  computed: {
      total: function() {
          return (this.words * this.preco).toLocaleString('de-DE')
      },
      words: function() {
        if(this.text.length == 0) {
            return 0
        } else {
            this.words = this.text.split(' ').length
            console.log(this.words)
            return this.text.split(' ').length
        }
      }
  },
  methods: {
      price: function () {
        axios.post('/service/price', {
            lang_origem: this.lang1,
            lang_dest: this.lang2
        })
        .then(function (response) {
            this.preco = response.data.price
            console.log(this.price)
        })
        .catch(function (error) {
            console.log(error);
        });
      }
  }
})

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    我可以在您的代码中看到的问题,

    • 数据和方法都有一个名为 price 的属性,它们会发生冲突。
    • preco 没有反应。如果它不是响应式的,则更改其值不会更新依赖于它的计算值。您应该将preco 添加到数据中以使其具有反应性。
    • 您应该在 axios 请求中使用arrow function。否则,this.preco = ... 中的 this 将不会引用 Vue 实例

    【讨论】:

    • 另一个冲突是在this.words 内部computed.words
    【解决方案2】:

    this.preco 将是空的,只要服务器调用(axios.post('/service/price' ...) 未完成,您需要将其重写为更新this.total 的方法 像这样的:

    {
            methods: {
                calcTotal: function () {
                    this.price()
                        .then(() => {
                            this.total = (this.words * this.preco).toLocaleString('de-DE')
                        })
                },
    
                price: function () {
                    //return so that we can wait on this to be finished
                    return axios.post('/service/price', {
                            lang_origem: this.lang1,
                            lang_dest: this.lang2
                        })
                        .then(function (response) {
                            this.preco = response.data.price
                            console.log(this.price)
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多