Ari
Ari

Reputation: 6189

How to edit the template depending on what data there is?

I have a Vue component that creates a <select> with <option>s. I want the options in the select to be dependent on a list.

Vue.component('column-header', {
    data: function() {
         return {
           options: ['Name', 'Address', 'Email', 'Mobile', 'Card Number', 'Other'],
         }
    },
    template: `<div class="uk-width-1-5">
                <select class="uk-select">
                    {{ options }}
                </select>
            </div>`
});

new Vue({ el: '#app' })

As I decide to expand my options list later, it should automatically insert the new item as an option. Is this the correct way to go about it?

Upvotes: 1

Views: 47

Answers (2)

strifel
strifel

Reputation: 44

You can use v-for to iterate over the array and create new options.

<select>
<option v-for="option in options" :key="option">{{ option }}</option>
</select>

Upvotes: 2

tony19
tony19

Reputation: 138536

Use v-for to render a list of elements:

<option v-for="option in options">{{option}}</option>

The options data property is reactive, so adding items to that array would automatically update the template to include the new <option> in the <select>.

Vue.component('column-header', {
    data: function() {
         return  {
           options: ['Name', 'Address', 'Email', 'Mobile', 'Card Number', 'Other'],
         }
    },
    template: `<div class="uk-width-1-5">
                <select class="uk-select">
                    <option v-for="option in options">{{option}}</option>
                </select>
                <button @click="addOption">Add option</button>
            </div>
            `,
  methods: {
    addOption() {
      this.options.push('Foo' + this.options.length);
    }
  }
});

new Vue({ el: '#app' })
<script src="https://unpkg.com/[email protected]"></script>

<div id="app">
  <column-header></column-header>
</div>

Upvotes: 2

Related Questions