Use AJAX Dynamic URL for Vue Select2 Shell Component

I changed the Wrapper Component Example from the VueJS documentation to include the AJAX data source option. Here is my code.

However, I would like to set the property of ajax url my select2 component dynamically as best as possible ,

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

How should I do it?

+1
source share
1 answer
  1. Add a property to the propscomponent:

    Vue.component('select2', {
        props: ['options', 'value', 'url'],
    
  2. Move the AJAX parameters either to a variable with a scope outside the select2 component, or to a data element of this 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 this variable when initializing select2:

    mounted: function() {
        var vm = this
        $(this.$el)
           .select2({
               placeholder: "Click to see options",
               ajax: this.ajaxOptions
           })
    
  4. Add an observer for the URL:

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

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

    url .

.

+3

Source: https://habr.com/ru/post/1694757/


All Articles