Home > Enterprise >  Vue.js get selected li item of ul
Vue.js get selected li item of ul

Time:07-16

I have a list displayed like a dropdown -

Each of the items except 'Create New Filter' is bound to a key so i can uniquely identify the li items.

I want to know how can i get the selected li item on save and do operations accordingly

What would be the good approach for this so i can understand when 'Create new filter' is clicked or when other li items are selected

enter image description here

Below is the code -

 <ul>
     <li v-on:click="create">Create New</li>
     <li v-for="item in list" :key="item.id" v-on:click="Change(item.id,item.text)">{{ item.text }}</li>
</ul>

CodePudding user response:

As per my understanding this approach is not good, I am not sure why you are building dropdown by using <ul> and <li> instead of select element as it is a form element and provide a better way to get the selected option value by the help of v-model directive.

Anyhow I worked as per your requirement and came up with the solution.

var app = new Vue({
  el: '.dropdown',
  data: {
    list: [{
      id: 1,
      text: 'First Filter'
    }, {
      id: 2,
      text: 'First Filter 2021'
    }, {
      id: 3,
      text: 'Full Filter'
    }],
    selectedListItem: null
  },
  methods: {
    create() {
      console.log('New filter Create Called');
    },
    getSelected (item) {
      this.selectedListItem = item;
    },
    save() {
      if (this.selectedListItem) {
        console.log(this.selectedListItem);
      } else {
        console.log('No list option selected');
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div >
  <input type="text" placeholder="Select Filter"  data-toggle="dropdown"/>
  <ul >
    <li v-on:click="create">Create New</li>
    <li v-for="item in list" :key="item.id" v-on:click="getSelected(item)">{{ item.text }}</li>
  </ul>
  <button @click="save">SAVE</button>
</div>

  • Related