1

I have a search input that searches through a JSON file - it works fine, I am now trying to display the number of results found to the user. (eg. '26 results found' - or 'No results found')

I am using a computed method that checks if the user has clicked on the search input, and then checks through the JSON file to match the user's query to a string in the JSON file. This is my current code:

    computed: {

    filteredPrizesByQuery: function() {
      if (this.searchInputClicked == true) {
        return this.prizes.filter(prize => {
          return (
            prize.prizeTitle.toLowerCase().match(this.query) || 
            prize.prizeTag.toLowerCase().match(this.query)
          )
        });
      } else
        return this.prizes.filter(prize => {
          return (
            prize.prizeType1Name.match(this.tabbedQuery) ||
            prize.prizeType2Name.match(this.tabbedQuery)
          );
        });
    }
  }

When I type in a query in the search box and then look at my Vue Dev Tools, I can see the Array count is updated (under computed) eg. filteredPrizesByQuery:Array[26]. This is the value I want to display to the user, but I can't figure out how to access this value.

I have tried checking the length of filteredPrizesByQuery or the length of 'prize' within the computed method, but I either get a maximum call stack size error or undefined.

1 Answer 1

4

You can simply create another computed property and access the filteredPrizesByQuery computed property length there like:

computed: {    
   filteredPrizesByQuery: function() {
      // Your current logic returning array here...
   },
   filteredPrizesCount: function() {
      return this.filteredPrizesByQuery.length;
   }
}

and then update UI like:

<p>{{filteredPrizesCount}} results found</p>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this worked. Can you please explain why I can't access this.filteredPrizesByQuery.length through a normal method, and why it has to be inside computed?
Actually, a computed property will only re-evaluate when some of its reactive dependencies have changed. Also, computed properties are cached based on their reactive dependencies. So, when you call length it is still looking at the initial array which is not evaluated yet. But when you use length inside filteredPrizesCount it forces it to re-evaluate as soon as filteredPrizesByQuery value changes.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.