oli
oli

Reputation: 53

(Vue.js) How can I populate the select tag with option tag from array of number values in data?

I would like to populate my select tag with options from an array variable which contains arrays of number values. But the values that are reproduced seems to be blank

HTML:

  <select required id="dropDown">
    <option>Select here</option>
    <option v-for="choice in choices">{{ choice }}</option>
  </select>

Javascript:

var vm = new Vue({   
el: 'body',    
data:{
    'choices': [1,2,3,4,5]
    }
});

Can someone point me of my mistake? Because I am just a beginner though, and I would like to learn from you guys.

Upvotes: 5

Views: 15373

Answers (2)

Enver
Enver

Reputation: 618

If you get your data from the backend, you need to follow another way. For example, I have a category list, which comes from the backend.

 <el-select
              v-model="categorySelect.selected"
              size="large"
              name="category_id"
              single
              v-bind:placeholder="$t('products.category')"
          >
            <el-option
                v-for="item in categorySelect.autocompleteItems"
                :key="item.id"
                :label="item.name_en"
                :value="item.id"
            ></el-option>
          </el-select>

Your script should looks like this :

categorySelect: {
    selected: [],
    autocompleteItems: this.categoriesItem,
  },

categoriesItem: {
      required: false,
      type: Object
    },

and then, you need to get your data on your view like this :

:categories-item="{{$categories}}"

as you see the above code, you can fill your select list with a different list that comes from the backend.

Enjoy Your Code!

Upvotes: 0

asemahle
asemahle

Reputation: 20805

The el option should provide Vue with an existing DOM element to mount on. You have provided a CSS selector for body, so Vue will try to mount on the body element.

Otherwise your code is correct. Just wrap your HTML in body tags and it works!

var vm = new Vue({   
  el: 'body',    
  data:{
    'choices': [1,2,3,4,5]
  }
});
<!-- Load Vue JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>

<!-- add body tags so `el: 'body'` resolves to an HTML element -->
<body>
  <select required id="dropDown">
    <option>Select here</option>
    <option v-for="choice in choices">{{ choice }}</option>
  </select>
</body>

Upvotes: 9

Related Questions