Search code examples
vue.jsv-select

how to pass value in v-select in vue


i m new to vue (version 2.5) in my project i had install v-select i go through document and got confuse on few thing here is my code

  <template>
   <div class="wrapper">


             <div class="row">
               <div class="col-sm-6">
                 <div class="form-group">
                   <label for="name">Category</label>
                   <v-select  label="category_desc" options="category"></v-select>
                 </div>
               </div>
          </div>
  <button type="button" variant="primary" class="px-4" @click.prevent="next()">next</button>
       </div>
 </template>     

 <script>
   export default {
     name: 'Addproduct',
    data () {
             return {

                 category:[]


             }
           },
     mounted() {
             this.$http.get('http://localhost:3000/api/categories') .then(function (response) {
                 console.log(response.data);
                this.category=response.data

                 })
                 .catch(function (error) {
                   console.log("error.response");
                 });
         },

method:{ next(){ // console.log('value of v-selection not option' ) eg id 1 has 'country' so i want id 1 in method next() i.e in console.log } } now my problem is that how i can pass this axios responded success value to v-select option and second this how i can get selected value of v-select for eg;- when user click on next button how i can get which value is selected in v-select


Solution

  • You need to bind options to category. i.e. v-bind:options or short hand :options I would also suggest you use a method to make your ajax call, and then call the method in mounted() instead. Also you probably want a v-model on that select so I added that in the example.

    First in your template...

     <v-select  v-model="selectedCategory" label="category_desc" :options="category"></v-select>
    

    Then in your script definition...

    data(){
       return{
         category:[],
         selectedCategory: null,
       }
    },
    methods:{
        getCategories(){
          this.$http.get('http://localhost:3000/api/categories')
               .then(function (response) {
                   this.category=response.data
                 }.bind(this))
               .catch(function (error) {
                   console.log("error.response");
                });
      }
    },
     mounted(){
       this.getCategories(); 
     }
    

    Here is a working jfiddle https://jsfiddle.net/skribe/mghbLyva/3/