2017-12-01 6 views
0

Vuejs 2.x에서 ajax 원격 데이터 옵션과 함께 select2를 사용하고 싶습니다. vuejs.org website에는 정적으로 작동하는 select2 구성 요소의 샘플이 있지만 내 프로젝트에는 this specific으로 select2를 사용해야합니다. JSFIDDLE Example을 키보드 유형으로 API를 호출하는 select2로 변환하는 방법 나를 위해 노력하고 있습니다Vuejs의 ajax 원격 데이터 옵션 구성 요소가 포함 된 Select2

$('.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'를 통해 바이올린의'options' prop로 전달합니다. –

+0

@lamelemon 감사합니다. 샘플 코드를 변경하십시오. 나도 몰라. –

답변

0
다음

입니다 구성 요소 : jQuery를 선택 2에서

는 아약스 호출이 코드를 사용합니다. 자신의 선택 2 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); 

    }); 
    } 
});