Why does v-for
behave different when using either numbers
or template literals
?
Here is an example:
new Vue({ el: "#app", })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <p>Result with template literal</p> <ul> <li v-for="pages in `${2+2}`" :key="pages" > <p>{{pages}}</p> </li> </ul> <p>Result with straight number</p> <ul> <li v-for="pages in 4" :key="pages" > <p>{{pages}}</p> </li> </ul> </div>
Advertisement
Answer
They are not the same. In the first one, you are using v-for
on a string. In which case, vue will loop through the characters and display each of them in a li
. In the second one, it’s an integer. In which case, vue will use the range mechanism
new Vue({ el: "#app", })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <p>Result with template literal</p> <ul> <!--Displays 1, 0, 0--> <li v-for="pages in `100`" :key="pages" > <p>{{pages}}</p> </li> </ul> <p>Result with straight number</p> <ul> <li v-for="pages in 4" :key="pages" > <p>{{pages}}</p> </li> </ul> </div>