为Vue Select2包装器组件使用动态AJAX URL

时间:2017-09-26 11:24:06

标签: javascript jquery vue.js vuejs2 jquery-select2

我修改了Wrapper Component Example 从VueJS文档中包含AJAX数据源选项。 Here是我的代码。

但是,我想动态设置select2组件的ajax url 属性,最好是这样,

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

我该怎么做?

1 个答案:

答案 0 :(得分:2)

  1. 添加属性:

    Vue.component('select2', {
        props: ['options', 'value', 'url'],
    
  2. 将AJAX选项移动到范围在select2组件之外的变量或该组件的数据元素:

    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. 在初始化select2时使用该变量:

    mounted: function() {
        var vm = this
        $(this.$el)
           .select2({
               placeholder: "Click to see options",
               ajax: this.ajaxOptions
           })
    
  4. url 添加观察程序:

    watch: {
        url: function(value) {
            this.ajaxOptions.url = this.url;
            $(this.$el).select2({ ajax: this.ajaxOptions});
       }
    
  5. 设置属性:

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

    其中url在应用的 data 对象中定义。

  6. 参见this plunker example中的演示。