【问题标题】:Vuejs - computed property based on other computed propertyVuejs - 基于其他计算属性的计算属性
【发布时间】:2020-02-05 12:08:56
【问题描述】:

我正在尝试从另一个计算属性中获取一个计算属性,如下所示:

var instance = new Vue({
    el: "#instance",
    data: {
        aha: ""
    },
    computed: {
        len: function(){
            return this.aha.length;
        },
        plus : function(){
            return this.len + 2;
        }
    }
});

这不起作用。当我尝试显示plus 时,我的模板中出现了NaN。有没有办法使这项工作? this question 的答案对我不起作用。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    data 组件中的属性必须是一个函数,所以在你的情况下应该这样写:

    data () {
     return {
       aha: ""
     }
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试访问 length 类型为 number 的字段。

      this.len 是数字,所以this.len.length 是未定义的。你只需要使用this.len:

      var instance = new Vue({
          el: "#instance",
          data: {
              aha: ""
          },
          computed: {
              len: function(){
                  return this.aha.length;
              },
              plus : function(){
                  return this.len+ 2;
              }
          }
      });
      

      【讨论】:

      • 对。愚蠢的错误。谢谢。
      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2018-05-30
      • 2018-05-27
      • 2017-08-23
      • 1970-01-01
      • 2018-05-12
      • 2019-02-11
      • 2014-01-07
      相关资源
      最近更新 更多