Search code examples
javascriptvue.jsvuejs2v-for

How to v-bind index from v-for while concatenate with data?


Below code is just an example of what I am working on, I am trying to not repeat gs-input component multiple time and just use index that i get from v-for and make v-bind work:

<template lang="pug">
  div(v-for="index in 4")
    gs-input(
      label="From",
      v-bind:prop1="values.key + index + vals" // Does not work
      v-bind:prop2="`values.key${index}vals`"  // Does not work
    )
</template>

<script>
import GsInput from './GlobalSettingInput'

export default {
  name: 'global-settings-form',
  components: { GsInput },
  data() {
    return {
      values: {
        key1vals: 'Val Lorem',
        key2vals: 'Val Ipsum',
        key3vals: 'Val Dolo',
        key4vals: 'Val Solo',
      }
    }
  },
}
</script>

Solution

  • I think this is because you need to use array instead of dot syntax to access the values:

    gs-input(
      label="From",
      v-bind:prop1="values['key' + index + 'vals']" // Does work
      v-bind:prop2="values[`key${index}vals`]"  // Does work
    )