【问题标题】:Vue: Refactoring a computed propertyVue:重构计算属性
【发布时间】:2020-11-27 03:19:11
【问题描述】:

我有以下按预期工作的计算属性。如果 3 个数据属性中的任何一个为空字符串,我希望它返回 true,并且如果任何字符串为“n/a”,我希望它返回 true:

             appNamesInvalid() {
                if (!this.preferredAppName1 || !this.preferredAppName2 || !this.preferredAppName3) {
                    return true;
                }
                if (this.preferredAppName1.toLowerCase().includes('n/a') || this.preferredAppName2.toLowerCase().includes('n/a') || this.preferredAppName3.toLowerCase().includes('n/a')) {
                    return true;
                }
                return false;
            },

我最初尝试这样做,但没有按预期工作,我不知道为什么:

   appNamesInvalid() {
        let appNames = [this.preferredAppName1, this.preferredAppName2, this.preferredAppName3];
        appNames.forEach(appName => {
            if (appName == "" || appName.toLowerCase().includes("n/a")) { 
               return true;
            }
        }
        return false;
    },

有没有更简洁的方法来重构第一个块中的工作代码?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    尝试使用 Array.prototype.some 根据您的特定条件返回布尔值:

    appNamesInvalid() {
      let appNames = [this.preferredAppName1, this.preferredAppName2, this.preferredAppName3];
      return appNames.some(appName => {
          return appName === "" || appName.toLowerCase().includes("n/a");
      }
    },
    

    如果appName === ""appName.toLowerCase().includes("n/a") 为真,则返回true

    希望对您有所帮助!

    【讨论】:

    猜你喜欢
    • 2020-02-03
    • 2019-10-25
    • 1970-01-01
    • 2021-05-04
    • 2022-11-11
    • 2020-12-01
    • 2017-06-30
    • 2019-09-22
    • 2019-10-03
    相关资源
    最近更新 更多