M
M
mazahaler2019-10-19 16:30:24
Vue.js
mazahaler, 2019-10-19 16:30:24

How to refactor computed methods in Vue?

Hello, how can I "refactor" this?

computed: {
            strengthHeroes() {
                return this.heroes.filter(hero => {
                    return hero.hero_attribute === 'Сила' && hero.name.toLowerCase().includes(this.searchHeroesString.toLowerCase())
                })
            },
            agilityHeroes() {
                return this.heroes.filter(hero => {
                    return hero.hero_attribute === 'Ловкость' && hero.name.toLowerCase().includes(this.searchHeroesString.toLowerCase())
                })
            },
            intelligenceHeroes() {
                return this.heroes.filter(hero => {
                    return hero.hero_attribute === 'Интеллект' && hero.name.toLowerCase().includes(this.searchHeroesString.toLowerCase())
                })
            },
        },

It would be great if you could pass parameters to computed properties, then 1 method would come out of it. And now I look at this, and in my head it starts "you repeat the same code, you repeat the same code ..."
Can this code be shortened somehow, while leaving the methods in computed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-10-19
@mazahaler

pass parameters <...> leaving computed

What about the meaning? There will be a computed property whose value is a function. No caching, just code complexity. Do the usual method:
methods: {
  filterHeroes(attr) {
    const s = this.searchHeroesString.toLowerCase();
    return this.heroes.filter(n => n.hero_attribute === attr && n.name.toLowerCase().includes(s));
  },

M
mazahaler, 2019-10-19
@mazahaler

Just did the usual method instead of all that. My heart felt lighter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question