2017-12-01 3 views
0

Vuejs 2.xでajaxリモートデータオプションでselect2を使用したいと考えています。 vuejs.org websiteでは、静的として動作するselect2コンポーネントのサンプルがありますが、私のプロジェクトにはthis specificでselect2を指定する必要があります。 JSFIDDLE ExampleをキーボードタイプのAPIを呼び出すselect2に変換する方法jQueryのSelectセレクトでVuejsのajaxリモートデータオプションコンポーネントを含むSelect2

はAJAX呼び出しのために、このコードを使用します。ここでは

$('.js-data-example-ajax').select2({ 
    ajax: { 
     url: 'https://api.github.com/search/repositories', 
     dataType: 'json' 
     // Additional AJAX parameters go here; see the end of this chapter for the full code of this example 
    } 
}); 
+1

何を試しましたか?あなたがする必要があるのは、Vueインスタンスの 'mounted'フックでajaxリクエストを起動し、返されたデータを' props'を通してコンポーネントに渡すことです。 –

+0

@lamelemonありがとう、サンプルコードを変更してください。私は知らない –

答えて

0

は私のために働いているコンポーネントです。私のために彼らのSELECT2への参照 https://vuejs.org/v2/examples/select2.html

落とし穴はchange.select2を使用して代わりの時計でchangeイベントをトリガーました。 changeイベントにより無限ループが発生します。

コールバック/ ajax URLは、少なくとも.idおよび.textプロパティを持つデータを返す必要があります。適切なフォーマットについては、URLを参照してください。https://select2.org/data-sources/formats

<select2 v-model="member" name="member" callback="/res/member/select2.php" placeholder="Type a name"></select2> 

Vue.component('select2', { 
    props: ['name', 'value', 'required', 'callback', 'placeholder'], 
    template: '<select :name="name" v-bind:class="{required: required}" class="vue-select2"></select>', 
    watch : { 
    value : function(value) { 
     $(this.$el).empty().append('<option value="' + value.id + '">' + value.text +'</option>').trigger('change.select2'); 
    } 
    }, 
    mounted: function() { 
    var that = this; 
    var options = { 
     width: '100%', 
     placeholder: this.placeholder, 
     allowClear: true, 
     ajax: { 
     url: this.callback, 
     dataType: 'json' 
     } 
    }; 
    $(this.$el).select2(options); 
    $(this.$el).on('change', function() { 
     var item = $(this).select2('data')[0]; 
     that.$emit('input', item); 

    }); 
    } 
}); 
関連する問題