0

I wanna to use select2 with ajax remote data options in Vuejs 2.x. In vuejs.org website located a sample for select2 component that work as static, but I need to select2 with this specific for my project. How to convert JSFIDDLE Example to select2 that call an API with keyboard type.

In jQuery Select2 use this code for ajax call:

$('.js-data-example-ajax').select2({
    ajax: {
      url: 'https://api.github.com/search/repositories',
      dataType: 'json'
      // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
    }
});
2
  • 1
    What have you tried? All you need to do is fire an ajax request in the mounted hook of the Vue instance and then pass the returned data to the component through props as the options prop in that fiddle. Commented Dec 1, 2017 at 14:32
  • @lamelemon thanks, please change sample code. I don't know to do Commented Dec 1, 2017 at 14:49

1 Answer 1

1

Here is component that is working for me. Reference to their select2 https://v2.vuejs.org/v2/examples/select2.html

The gotcha for me was using change.select2 instead of triggering change event in the watch. change event causes infinite loop.

Your callback/ajax URL will need to return data with at least .id and .text properties. See this URL for proper format https://select2.org/data-sources/formats

 <select2 v-model="member" name="member" callback="/res/member/select2.php" placeholder="Type a name"></select2>

Vue.component('select2', {
  props: ['name', 'value', 'required', 'callback', 'placeholder'],
  template: '<select :name="name" v-bind:class="{required: required}" class="vue-select2"></select>',
  watch : {
    value : function(value) {
      $(this.$el).empty().append('<option value="' + value.id + '">' + value.text +'</option>').trigger('change.select2');
    }
  },
  mounted:  function() {
    var that = this;
    var options = {
      width: '100%',
      placeholder: this.placeholder,
      allowClear: true,
      ajax: {
        url: this.callback,
        dataType: 'json'
      }
    };
    $(this.$el).select2(options);
    $(this.$el).on('change', function() {
      var item = $(this).select2('data')[0];
      that.$emit('input', item);
     
    });
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.