Thomas Miller
Thomas Miller

Reputation: 115

Vue v-for loop binding attribute

I'm trying to figure out how to do this in vue, I'm stuck trying to bind the value of the "selected" in the options.

In the simplified code below, I get exactly what I want, but only for the first product. It binds correctly with the first computed property:

<template>
  <div>
    <div v-for="index in 2" :key="index">
      <select>
        <option :selected="product1 === ''">Empty</option>
        <option
          v-for="(product, index) of products"
          :key="index"
          :selected="product1 === product.name"
        >{{product.name}}</option>
      </select>
    </div>
  </div>
</template>

<script>
  // chosen products come from vuex store
  computed: {
    product1() {
      return store.state.product1;
    },
    product2() {
      return store.state.product2;
    },
  }
</script>

But then how can I change this to be automatic in the v-for loop, probably using the index?

What I need is actually a loop that will render this:

<template>
  <div>
    <select>
      <option :selected="product1 === ''">Empty</option>
      <option
        v-for="(product, index) of products"
        :key="index"
        :selected="product1 === product.name"
        >{{product.name}}
      </option>
    </select>
    <select>
      <option :selected="product2 === ''">Empty</option>
      <option
        v-for="(product, index) of products"
        :key="index"
        :selected="product2 === product.name"
        >{{product.name}}
      </option>
    </select>
  </div>
</template>

I've tried using something like:

:selected="`product${index}` === product.name"

but that gives a string, not the computed property value...

Upvotes: 0

Views: 1714

Answers (2)

Efrat Levitan
Efrat Levitan

Reputation: 5612

you can pass parameter to your computed property:

<template>
  <div>
    <div v-for="index in 2" :key="index">
      <select>
        <option :selected="getProduct(index) === ''">Empty</option>
        <option
          v-for="(product, index) of products"
          :key="index"
          :selected="getProduct(index) === product.name"
        >{{product.name}}</option>

<script>
  // chosen products come from vuex store
  computed: {
    getProduct() {
      return index=>
           store.state['product'+index];
    },
  }
</script>

Upvotes: 2

akuiper
akuiper

Reputation: 214927

You can put the selected products in an array and then access it by index:

computed: {
  selectedProducts () {
    return [store.state.product1, store.state.product2];
  }
}

And then you can do :selected="selectedProducts[index] === product.name".

Upvotes: 0

Related Questions