Search code examples
loopsvue.jsfor-loopvue-componentv-for

How Key and value Iterate in Vue Js


I'm trying to iterate bellow array with key and value in vue.js.

attributes = {"Size - UK":"12","Color":"White"}.

this array is getting from database as string

I want result as below

Size : 12 Color : White

I used below method to do that

 <span :v-for="(item, index) in attributes">
     {{item}} : {{index}}
 </span>

and I got an error like this.

Property or method "index" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

How can I fix this?


Solution

  • The v-for attribute should not have : (see the docs)

    Try this with : removed:

    // https://codepen.io/collection/naevzw/
    var example1 = new Vue({
      el: '#example-1',
      data: {
        items:
          { message: 'Foo', text: 'Bar', other: 'FooBar' }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <!-- v-for - VUE.js Guide Example -->
    <ul id="example-1">
      <li v-for="(key) in Object.keys(items)">
        {{ key }} : {{ items[key] }}
      </li>
    </ul>