0
votes

I'm running through a list of cart items in vue and need to get the index of each item. I thought you'd simply do something like this

  <ul class="crt-Push_Items">
    <li class="crt-Push_Item" v-for="(lineItem, index) in lineItems" :key="lineItem.key">
      <PushCartItem :lineItem="lineItem" />
    </li>
  </ul>

And

<p class="crt-PushItem_Price"><span class="money" data-line-index="{{ index }}">{{ formatMoney(lineItem.line_price) }} </span></p>

But this isn't displaying and I'm getting the error [Vue warn]: 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. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

3
this: data-line-index="{{ index }}" doesn't look like vue. Don't you mean :data-line-index="index"Thomas Kuhlmann
@ThomasKuhlmann fair point even though if I just did <p class="crt-PushItem_Price"><span class="money">{{ formatMoney(lineItem.line_price) }} {{ index }}</span></p> it's still not workingMariaL
Try switching from v-for=... in ... to v-for=... of .... And if that doesn't work, can you show the entire code?Thomas Kuhlmann

3 Answers

1
votes

I'm assuming that this line

<p class="crt-PushItem_Price"><span class="money" data-line-index="{{ index }}">{{ formatMoney(lineItem.line_price) }} </span></p>

is the PushCartItem component, so in order to receive the index property, you need to use props, because otherwise you can't have access to it, like this:

<template>
  <p class="crt-PushItem_Price">
    <span class="money" :data-line-index="index">
      {{ formatMoney(lineItem.line_price) }}
    </span>
  </p>
</template>
<script>
export default {
  name: 'PushCartItem',
  props: {
    index: {
      type: Number,
      required: true
    },
    lineItem: {
      type: Object,
      required: true,
    }
  },
  methods: {
    formatMoney(price) {
      // do something with the price
    }
  }
}
</script>

This answer is based in my assumptions, if you still having the error, please give me more information or details about it to help you.

0
votes

You need to pass the index from the parent component like this.

<ul class="crt-Push_Items">
<li class="crt-Push_Item" v-for="(lineItem, index) in lineItems" :key="lineItem.key">
  <PushCartItem :lineItem="lineItem" :index="index" />
</li></ul>
0
votes

Try this:

<ul class="crt-Push_Items">
    <li class="crt-Push_Item" v-for="(lineItem) in lineItems" :key="lineItem.key">
      <PushCartItem :lineItem="lineItem" />
    </li>
  </ul>

Or this:

<ul class="crt-Push_Items">
    <li class="crt-Push_Item" v-for="(lineItem, index) in lineItems" :key="index">
      <PushCartItem :lineItem="lineItem" />
    </li>
  </ul>