简体   繁体   中英

Vue.js 2 v-for loop doesn't get array element

I'm trying to check if an element is an Array. If true then print the elements of the array, else print the element.

My code does not print the element and I don't know where there is a problem.

HTML :

<div>
<ul>
<li v-for="(value, i) in testData" :key="i">
<template v-if="Array.isArray(value)">
<div v-for="(element, ind) in value" :key="ind">{‌{ element }}</div>
</template>
<template v-else> {‌{ value }} </template>
</li>
</ul>
</div>

Script :

export default {   
data() {
return {
testData: {
id: 1,
name: "MyTest",            
data: [1,0.5,5,8],
},}}

MyOtput :

{‌{ value }}
{‌{ value }}
{‌{ element }}
{‌{ element }}
{‌{ element }}
{‌{ element }}

The first curly brace {{ of each interpolation expression in your post has an extra, invisible unicode character. I'm not sure how you created that but it causes the problem.

When copy-pasting the braces {{ into this Unicode text analyzer it shows that there are 3 characters:

  • { = U+007B LEFT CURLY BRACKET
  • = U+200C ZERO WIDTH NON-JOINER ❌ Should not be here
  • { = U+007B LEFT CURLY BRACKET

With correct braces, your code does work:

 new Vue({ el: "#app", data() { return { testData: { id: 1, name: "MyTest", data: [1,0.5,5,8] } } } });
 <div id="app"> <ul> <li v-for="(value, i) in testData":key="i"> <template v-if="Array.isArray(value)"> <div v-for="(element, ind) in value":key="ind">{{ element }}</div> </template> <template v-else>{{ value }}</template> </li> </ul> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM