Home » vue » Vue.js single file component for loop error

Vue.js single file component for loop error

Posted by: admin November 26, 2021 Leave a comment

Questions:

For some reason i cannot get a loop working within a single file .vue file. The following error occurs:

Property or method “value” 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.

(Getting the same error for the key value)

.vue File:

<template>
  <div class="grid-view container mx-auto flex items-center py-4">
    <div v-bind:for="(value, key) in testdata">
      {{ key }}: {{ value }}
    </div>
  </div>
</template>

<script>
export default {
  props: [
    'testdata'
  ]
}
</script>

HTML:

<test :testdata="{'name':'sku','name':'test'}"></test>

Hope someone can help!

Answers:

Replace v-bind:for= with v-for=

<template>
  <div class="grid-view container mx-auto flex items-center py-4">
    <div v-for="(value, index) in testData" :key="index">
      {{ value }}
    </div>
  </div>
</template>

<script>
export default {
  props: [
    'testData'
  ]
}
</script>

Your test data is not correct as you’re using one object which contains two similar name keys:

<test :test-data="{'name':'sku','name':'test'}"></test>

..so put each object into an array:

<test :test-data="[{ name: "sku" }, { name: "test" }]"></test>

A note for code conventions:

When naming the props in HTML, use kebap case:

:test-data instead of :testdata

When naming the props in JS, use camel case:

testData instead of testdata

###

Change v-bind:for to v-for

<template>
  <div class="grid-view container mx-auto flex items-center py-4">
    <div v-for="(value, key) in testdata">
      {{ key }}: {{ value }}
    </div>
  </div>
</template>

<script>
export default {
  props: [
    'testdata'
  ]
}
</script>