@codharma

Как переписать эту лапшу?

Как сделать этот код более DRY?

showButton () {
      if (this.$route.name === 'new-article') {
        if (this.article.section && this.article.title && this.article.description) {
          return true
        } else return false
      }
      if (this.$route.name === 'update-article') {
        if (this.show && this.article.section && this.article.title && this.article.description) {
          return true
        } else return false
      }
    }


Есть ощущение что можно обойтись без повторения блоков и излишней вложенности
  • Вопрос задан
  • 268 просмотров
Пригласить эксперта
Ответы на вопрос 5
sfi0zy
@sfi0zy Куратор тега JavaScript
Creative frontend developer
showButton () {
    switch (this.$route.name) {
        case 'new-article':
            return this.article.section &&
                   this.article.title &&
                   this.article.description;
        case 'update-article':
            return this.show &&
                   this.article.section &&
                   this.article.title &&
                   this.article.description;
    }
}
Ответ написан
@TheAthlete
Perl 5, C, C++, компьютерные сети
Решение в лоб:

showButton () {
  if (this.$route.name === 'new-article') {
    return !!(this.article.section && this.article.title && this.article.description);
  }
  if (this.$route.name === 'update-article') {
    return !!(this.show && this.article.section && this.article.title && this.article.description);
  }
}


с выносом в отдельную переменую повторяющихся частей

showButton() {
  var is_sect_title_descr = !!(this.article.section && this.article.title && this.article.description);
  if (this.$route.name === 'new-article')    { return is_sect_title_descr; }
  if (this.$route.name === 'update-article') { return this.show && is_sect_title_descr; }
}
Ответ написан
Комментировать
voronkovich
@voronkovich
showButton () {
    if (!this.article.section || !this.article.title || !this.article.description) {
        return false;
    }

    if (this.$route.name === 'new-article') {
        return true;
    }

    if (this.$route.name === 'update-article' && this.show) {
        return true;
    }

    return false;
}
Ответ написан
Комментировать
TDerden
@TDerden
showButton () {
return (((this.$route.name === 'update-article')?this.show:true) && this.article.section && this.article.title && this.article.description);
}
Ответ написан
@MrTimon
Зачем эти повторения и ф-ции не могу понять. Как по мне проще сделать так
showButton () {
    return in_array(this.$route.name, ['new-article','update-article'] ) && this.article.section && this.article.title && this.article.description;
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы