Search code examples
javascriptvuejs2bootstrap-selectpicker

Using Vue how do you call a function when a user clicks on a bootstrap-selectpicker option


I have multiple selectpickers in a vue component when a user clicks on an option I want to call a function passing in an id

<tr v-for="(content) in searchResults" v-bind:key="content.id">
   <td>{{ content.title}}</td>
    <td>
        <select class="selectpicker">
            <option value="" selected disabled>Select Option</option>
            <option value="Reject" @v-on:click="rejectArticle(content.id)">Reject</option>
            <option value="Preview" @v-on:click="previewArticle(content.id)">Preview</option>
            <option value="Approve" @v-on:click="approveArticle(content.id)">Approve</option>
        </select>
    </td>
</tr>

However this is wrong. What is the correct way to accomplish this?


Solution

  • I think the easiest way is to use @change, as noted in the response, this is how that would look like template: @change="onChange($event, content.id)"

    in the handler, you can then access the value with event.target.value

    new Vue({
      el: "#app",
      data: { searchResults:[{id:1, title:'ABC'}, {id:2, title:'DEF'}] },
      methods: {
      	onChange(event, id) {
       	  console.log(event.target.value, id)
          switch (event.target.value) {
            case rejectArticle:
              this.rejectArticle(id)
              break;
    
            case previewArticle:
              this.previewArticle(id)
              break;
    
            case approveArticle:
              this.approveArticle(id)
              break;
    
            default:
              break;
          }
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
    <div id="app">
     <table>
      <tr v-for="(content) in searchResults" v-bind:key="content.id">
         <td>{{ content.title}}</td>
          <td>
              <select class="selectpicker" @change="onChange($event, content.id)">
                  <option value="" selected disabled>Select Option</option>
                  <option value="Reject">Reject</option>
                  <option value="Preview">Preview</option>
                  <option value="Approve">Approve</option>
              </select>
          </td>
      </tr>
     </table>
     </div>