Use dynamic AJAX URL for Vue Select2 wrapper component

假装没事ソ 提交于 2020-01-01 19:20:53

问题


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:


  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.



来源:https://stackoverflow.com/questions/46425172/use-dynamic-ajax-url-for-vue-select2-wrapper-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!