Eden M
Eden M

Reputation: 171

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 }}

Upvotes: 1

Views: 582

Answers (1)

Dan
Dan

Reputation: 63129

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>

Upvotes: 1

Related Questions