1

I modified the Wrapper Component Example from the VueJS documentation to include the AJAX datasource option. Here is my code.

However, I would like to set the ajax url property of my select2 component dynamically preferably like this,

<select2 :options="options" v-model="selected" url="dynamic-url-here">
  <option disabled value="0">Select one</option>
</select2>

How would I do this?

1 Answer 1

3
  1. Add the property to the Component's props:

    Vue.component('select2', {
        props: ['options', 'value', 'url'],
    
  2. Move the AJAX options either to a variable with scope outside the select2 component or a data element of that component:

    Vue.component('select2', {
        props: ['options', 'value', 'url'],
        template: '#select2-template',
        data: function() {
          return {
              ajaxOptions: {
                  url: this.url,
                  dataType: 'json',
                  delay: 250,
                  tags: true,
                  data: function(params) {
                      return {
                          term: params.term, // search term
                          page: params.page
                      };
                  },
                  processResults: function(data, params) {
                      params.page = params.page || 1;
                      return {
                          results: data,
                          pagination: {
                              more: (params.page * 30) < data.total_count
                          }
                      };
                  },
                  cache: true
              }
          };
      },
    
  3. use that variable when initializing the select2:

    mounted: function() {
        var vm = this
        $(this.$el)
           .select2({
               placeholder: "Click to see options",
               ajax: this.ajaxOptions
           })
    
  4. Add a watcher for url:

    watch: {
        url: function(value) {
            this.ajaxOptions.url = this.url;
            $(this.$el).select2({ ajax: this.ajaxOptions});
       }
    
  5. Set the property:

    <select2 :options="options" v-model="selected" :url="url">
    

    where url is defined in the data object of the app.

See a demonstration in this plunker example.

Sign up to request clarification or add additional context in comments.

2 Comments

I found a temporary work around by adding data-url property to <select2> tag and fetching it in my component using vm.$el.dataset.url,. This is great, Thank you.
It works but how to call ajax only after 3 char entered @SAMOnela

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.