Use dynamic AJAX URL for Vue Select2 wrapper compo

2019-06-02 04:23发布

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条回答
叛逆
2楼-- · 2019-06-02 05:06
  1. Add the property:

    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.

查看更多
登录 后发表回答