ImranR
ImranR

Reputation: 516

How can I get the length of a computed array in Vue.js

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.

Upvotes: 1

Views: 5574

Answers (1)

palaѕн
palaѕн

Reputation: 73926

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>

Upvotes: 4

Related Questions