How to get the total length of an array in Vue.js
P粉908138620
P粉908138620 2023-07-27 21:43:09
0
1
657
<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粉908138620
P粉908138620

reply all(1)
P粉668146636

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;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template