[Vuejs]-How can I use foreach in a Vue select?

3πŸ‘

To its very simple to make a nesteed selector in vuejs

// Initialize the vue instance
var app = new Vue({
  el: '#app',
  // Initialize the data, in the case that you are using Laravel
  //and Blade for example here is where you will need to retrive
  //all the categories like:
  // data: {{ Category::with(['subcategories'])->get() }}
  data: {
    categorySelected: null,
    subcategorySelected: null,
    message: 'Hello Vue!',
    categories: [
      {
        name: 'news',
        subcategories: [
          {
            name: 'sport'
          },
          {
            name: 'international'
          }
        ]
      },
      {
        name: 'blog',
        subcategories: [
          {
            name: 'a blog subcategpry example'
          },
          {
            name: 'another blog subcategpry example'
          }
        ]
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <label>Category Selectded : {{ categorySelected ? categorySelected.name : null }}</label> <br>
  <label>Subcategory Selectded : {{ subcategorySelected ? subcategorySelected.name : null }}</label> <br>
  <select v-model="categorySelected">
     <optgroup v-for="category in categories" :label="category.name">  
      <option
        v-for="subcategory in category.subcategories"
        :value="subcategory"
      >
        {{subcategory.name}}
      </option>
    </optgroup>
  </select>
<div>
πŸ‘€Diego Meza

-4πŸ‘

Try this.
Js:

let vm = new Vue({
    el: "#app",
    data: {
        integer: [{
            id: 1,
            name: 'odd',
            numbers: [{id: 1, name: 'one'}, {id: 3, name: 'three'}]
        }, {
            id: 2,
            name: 'even',
            numbers: [{id: 2, name: 'two'}, {id: 4, name: 'four'}]
        }],
    },
});

HTML:

<option v-for="item in integer" :value="item.id" v-text="item.name"></option>
    <option v-for="num in item.numbers" :value="num.id" v-text="num.name"></option>
πŸ‘€zBlade KGR

Leave a comment