search

Home  >  Q&A  >  body text

How to get the total length of an array in Vue.js

<p><span style="color:#383D41;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";font-size:16px;white-space:normal;background-color:#FFFFFF;"> I'm trying to get the total result length but I'm not getting anything in my template . This is my script:</span></p> <pre class="brush:php;toolbar:false;">data() { return { searchResults: [], totalResults: [], }} const response = await axios.post( "http://localhost:5000/api/search", searchData ); this.searchResults = response.data.Response.Results; // Set the search results in the component's data // Retrieve the traceId from the response const nestedResults = response.data.Response.Results; const totalResults = nestedResults[0].length; console.log("Total Results:", totalResults);</pre> <p>This is my console and I get the totalResults. </p> <pre class="brush:php;toolbar:false;">Total Results: 12</pre> <p>This is my template. </p> <pre class="brush:php;toolbar:false;"><p>Total Results: {{ totalResults }}</p></pre> <p>The template returned this. </p> <pre class="brush:php;toolbar:false;">Total Results: []</pre> <p>I get nothing in my template, what should I do? </p>
P粉908138620P粉908138620486 days ago646

reply all(1)I'll reply

  • P粉668146636

    P粉6681466362023-07-28 14:31:53

    First, you are initializing a variable that is supposed to be a number with an empty array. You should write like this:

    data() {
        return {
          searchResults: [],
          totalResults: 0,
    }}

    Secondly, you are not assigning the value to the correct totalResults variable, you are just declaring a new variable. To assign values ​​to totalResults, you should use this.totalResults. Therefore, the correct way to write it is:

    this.totalResults = nestedResults[0].length;

    reply
    0
  • Cancelreply