JSFiddle - React, Tailwind, and code Playground

by kzima

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/0.12.9/vue.min.js"></script>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<div id="el">
  <p>Selected: {{selected}}</p>
  <select v-select="selected" options="options">
    <option value="0">default</option>
  </select>
</div>

CSS

select {
  min-width: 300px;
}

JavaScript

// Let's use a custom directive to wrap the select2 library
// so that we can reuse it easily in any part of our Vue.js app.

Vue.directive('select', {
  
  // Since we expect to sync value back to the vm,
  // we need to signal this is a two-way directive
  // so that we can use `this.set()` inside directive
  // functions.
  twoWay: true,

  bind: function () {
    var optionsData
    // retrive the value of the options attribute
    var optionsExpression = this.el.getAttribute('options')
    if (optionsExpression) {
      // if the value is present, evaluate the dynamic data
      // using vm.$eval here so that it supports filters too
      optionsData = this.vm.$eval(optionsExpression)
    }
    // initialize select2
    var self = this
    $(this.el)
      .select2({
        data: optionsData
      })
      .on('change', function () {
        // sync the data to the vm on change.
        // `self` is the directive instance
        // `this` points to the <select> element
        self.set(this.value)
      })
  },

  update: function (value) {
    // sync vm data change to select2
    $(this.el).val(value).trigger('change')
  },

  unbind: function () {
    // don't forget to teardown listeners and stuff.
    $(this.el).off().select2('destroy')
  }
})

// now just boot the app
var vm = new Vue({
  el: '#el',
  data: {
    selected: 0,
    // make sure the data format conforms to what
    // select2 expects.
    options: [
      { id: 1, text: 'hello' },
      { id: 2, text: 'what' }
    ]
  }
})