0

I create a filter function and I want to show the result. Here's the code

    data() {
        return {
            questionList: faqData.flatMap(q => q.questions)
        }
    },
    computed: {
        search() {
            return this.$store.state.search
        },
        filter: function() {
            this.questionList.filter((x) => {
                return x.question.match(this.search);
            })
        }
    }

There's no problem with the questionList variable and the search() function. And I think the problem is in the filter() function. Anyway, here's my questionList

[{id: 1, question: 'blabla', answer: 'blabalbla'}, {id: 2, question: 'blabla', answer: 'blabalbla'}, {id: 3, question: 'blabla', answer: 'blabalbla'} ]

the filter function shows an empty array. Can anyone tell me where did I do it wrong? Thanks!

1
  • Why would you want to save the computed function to a variable anyway? this.result and this.filter are completely the same. Commented Feb 25, 2021 at 2:03

2 Answers 2

1

Computed properties' values are defined by what their functions return.

In your case undefined since filter: function() { does not return anything.

It is not a good idea at all to assign a state variable inside a computed property function!

The correct way to do it is:

    filter: function() {
        return this.questionList.filter((question) => {
            return question.title.match(this.search);
        })
    }
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your explanation! I actually wrote that code previously, without saving in a variable called result. But the problem is I want to loop the result of this filter function, like this v-for="x in filter" but it doesn't work. Any suggestions?
How doesn't it work? Can you link to a reproduction?
0
<template>
  <div class="hello">   
    <div>
      <p v-for="(item, index) in filt" :key="index">
        {{item.question}}
      </p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      questionList: faqData.flatMap(q => q.questions)
    }
  },
  computed: {
        search() {
            return this.$store.state.search;
        },
        filt: function() {
            return this.questionList.filter((x) => {
                return x.question.match(this.search);
            })
        }
    }
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.