[Vuejs]-Vuejs2 and chosen select issue

3👍

Here it is implemented as a wrapper component that supports v-model and a slot for the options. This makes it a drop-in replacement for a standard select widget, at least as far as basic functionality. The updated(), happily, will notice changes to the options list as well as to the value.

Since two-way directives are not supported in Vue2, I do not believe there is a way to implement this as a directive. If you really need that, you will want to use Vue1.

var vm = new Vue({
  el: '#search-results',
  data: {
    city: 'Toronto',
    cities: [{
      text: 'Toronto',
      value: 'Toronto'
    }, {
      text: 'Orleans',
      value: 'Orleans'
    }]
  },
  components: {
    'chosenSelect': {
      template: '<select class="cs-select" v-model="proxyValue" ><slot></slot></select>',
      props: ['value', 'options'],
      computed: {
        proxyValue: {
          get() {
            return this.value;
          },
          set(newValue) {
            this.$emit('input', newValue);
          }
        }
      },
      mounted() {
        $(this.$el)
          .chosen({
            inherit_select_classes: true,
            width: '30%',
            disable_search_threshold: 999
          })
          .change((ev) => {
            this.proxyValue = ev.target.value;
          });
      },
      updated() {
        $(this.$el).trigger('chosen:updated');
      }
    }
  }
});

setTimeout(() => { vm.cities.push({text: 'Houston', value: 'Worth it'}); }, 1000);
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.proto.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<div id='search-results'>
  Vue model value
  <br> {{city | json}}
  <hr> Select value:
  <chosen-select v-model="city">
    <option v-for="item in cities" :value="item.value">{{item.text}}</option>
  </chosen-select>

  <select v-model="city">
    <option v-for="item in cities" :value="item.value">{{item.text}}</option>
  </select>
</div>
👤Roy J

Leave a comment