2016-04-23 70 views
0

我將jQuery select2插件封裝在自定義指令中進行集成。Select2和Vue指令

export default { 

    data() { 
     return { 
      selected: null, 
      options: [] 
     } 
    }, 

    ready() { 
    this.fetchUsers() 
} 

    methods: { 
     fetchUsers: function() { 
      this.$http({ 
       url: '/api/users/get-all', 
       method: 'GET' 
      }).then(function (response) { 
       this.$set('options', response.data) 
      }, function (response) { 
       // error callback 
      }); 
     } 
    }, 

    directives: { 
     select: { 
      twoWay: true, 
      priority: 1000, 

      params: ['options'], 

      bind: function() { 
       var self = this; 

       $(this.el) 
         .select2({ 
          theme: "bootstrap", 
          closeOnSelect: true, 
          minimumInputLength: 3, 
          data: this.params.options 
         }) 
         .on('change', function() { 
          self.set(this.value) 
         }) 
      }, 
      update: function (value) { 
       $(this.el).val(value).trigger('change') 
      }, 
      unbind: function() { 
       $(this.el).off().select2('destroy') 
      } 
     } 
    } 

} 

和HTML:

<select v-select="selected" :options="options"></select> 

我試圖讓所有的用戶,並設置在fetchUsers功能選項,但似乎fetchUsers函數後選擇2指令執行,從而可變的選項始終是空的。

那麼如何通過ajax(vue-resource)獲取所有用戶,然後填充到select2?

回答

1

我有一個類似的問題與選擇2,只好用paramwatchers檢查時選項進行了更新:

select: { 
    twoWay: true, 
    priority: 1000, 

    params: ['options'], 

    paramswatchers: { 
     "options": function (val, oldVal) { 
      $(this.el).select2({ 
       data: val 
      }) 
     } 
    } 

    bind: function() { 
     var self = this; 

     $(this.el).select2({ 
      theme: "bootstrap", 
      closeOnSelect: true, 
      minimumInputLength: 3, 
      data: this.params.options 
     }) 
     .on('change', function() { 
      self.set(this.value) 
     }) 
    }, 
    update: function (value) { 
     $(this.el).val(value).trigger('change') 
    }, 
    unbind: function() { 
     $(this.el).off().select2('destroy') 
    } 
} 

來源:https://vuejs.org/guide/custom-directive.html#params

+0

非常感謝你:d:d。但paramsWatchers更確切地說:D和我是否需要更改:選項到v-bind:選項如文檔? – user3118789