Home > database >  Vue.js binding in select dropdwon
Vue.js binding in select dropdwon

Time:07-25

I have the below dropdown -

<select v-model="currentFilter" :title="filterName" @change="changeDropdwnFilter($event)">
<option>Show All Columns</option>
<option v-for="item in filters" :title="item.ice_name" :value="item.id">{{ item.ice_name }}</option></select>

I want to assign a value to 'Show All Column' such that in changeDropdwnFilter function i can understand if this value is selected and do separate logic. What is the good way of doing this?

CodePudding user response:

Include below object into your "filters" array

{id:-1,
ice_name:
"Show All"}

when every change event raised you need to write login if(id =='-1') then you need assume is it show all or otherwise it is specific selection

CodePudding user response:

You need to do changes as below.

On select tag changes:

<select v-model="currentFilter" :title="filterName" @change="changeDropdwnFilter($event)">
    <option value="ALL">Show All Columns</option>
    <option v-for="item in filters" :title="item.ice_name" :value="item.id">{{ item.ice_name }}</option>
</select>

on script side method changes.

methods: {
    changeDropdwnFilter(event) {
        // You can get value as below
        console.log(event.target.value)
        if(event.target.value === 'ALL'){
            // Write different logic for Show all columns here.
        }
    }
}

CodePudding user response:

Observations :

  • As you are using v-model directive in the select element. You can access the selected option value directly. Hence, you can ignore passing $event in changeDropdwnFilter method.
  • You can assign any meaningful value to the option Show All Columns. i.e. all

Live Demo :

new Vue({
  el: '#app',
  data: {
    currentFilter: null,
    filters: [{
        id: 1,
      ice_name: 'Option 1'
    }, {
        id: 2,
      ice_name: 'Option 2'
    }, {
        id: 3,
      ice_name: 'Option 3'
    }, {
        id: 4,
      ice_name: 'Option 4'
    }]
  },
  methods: {
    changeDropdwnFilter() {
        if (this.currentFilter === 'all') {
        // write logic for 'all' option selected
        console.log('Show All Columns option selected');
      } else {
        console.log(this.currentFilter);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="currentFilter" @change="changeDropdwnFilter">
<option value="all">Show All Columns</option>
<option v-for="item in filters" :value="item.id">{{ item.ice_name }}</option></select>
</div>

  • Related