是否有“Vue方式”来检查除if / else语句之外的空字符串变量?

时间:2018-04-13 04:16:35

标签: javascript vue.js vuejs2

我正在学习如何使用Vue并且无法绕着“vue”方式绕着头做事。

我是否可以使用Vue函数或方法来编写这么多语句?

    this.catArr = []

    if (cat === 'All Modules') {
      if (this.assetType !== '') {
        this.catArr.push(this.assetType)
      }
      if (this.assetFormat !== '') {
        this.catArr.push(this.assetFormat)
      }
      if (this.assetUse !== '') {
        this.catArr.push(this.assetUse)
      }
      this.catArr.push(this.assetMod)
    } else if (cat === 'All Types') {
      if (this.assetMod !== '') {
        this.catArr.push(this.assetMod)
      }
      if (this.assetFormat !== '') {
        this.catArr.push(this.assetFormat)
      }
      if (this.assetUse !== '') {
        this.catArr.push(this.assetUse)
      }
      this.catArr.push(this.assetType)
    } else {
      if (this.assetMod !== '') {
        this.catArr.push(this.assetMod)
      }
      if (this.assetType !== '') {
        this.catArr.push(this.assetType)
      }
      if (this.assetFormat !== '') {
        this.catArr.push(this.assetFormat)
      }
      if (this.assetUse !== '') {
        this.catArr.push(this.assetUse)
      }
    }

2 个答案:

答案 0 :(得分:2)

在vanilla JS中,通过编写DRY代码很容易实现。事先定义所有属性,定义属性以显式测试每个类别的 ,当创建数组时,只需迭代属性名称并相应地测试它们:

const props = ['assetType', 'assetFormat', 'assetUse', 'assetMod'];
const catPropsNotToTest = {
  'All Modules': ['assetMod'],
  'All Types': ['assetType'],
  default: [],
};

// ...

const propsNotToTest = catPropsNotToTest[cat] ? catPropsNotToTest[cat] : catPropsNotToTest.default;
this.catArr = props.reduce((propArr, propName) => {
  if (propsNotToTest.includes(propName)) propArr.push(this[propName]);
  else if (this[propName] !== '') propArr.push(this[propName]);
  return propArr;
}, []);

答案 1 :(得分:0)

我无法找到" Vue"我的研究方式,但我能够简化逻辑。

   this.catArr = []

    if (this.assetType !== '') {
      this.catArr.push(this.assetType)
    }
    if (this.assetFormat !== '') {
      this.catArr.push(this.assetFormat)
    }
    if (this.assetUse !== '') {
      this.catArr.push(this.assetUse)
    }
    if (this.assetMod !== '') {
      this.catArr.push(this.assetMod)
    }
相关问题