2017-11-14 2 views
0

Vue와 함께 Jquery Chosen을 사용하고 있습니다. 상태는 그것이 기대에 따라 잘 작동하지만 가져올 경우 상태는 동적입니다 선택한 가치를 정적 값을 할당하는 경우Vue 지시어가 값을 업데이트하지 않습니다 - Jquery Chosen

<chosen-select v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID"> 
         <option :value="null">Please select an option</option> 
         <option v-for="(state, index) in states" :key="index" :value="state.sid">{{state.nm}}</option> 
        </chosen-select> 

:

Vue.component("chosen-select", { 
    props: { 
     value: [String, Array], 
     multiple: Boolean 
    }, 
    template: `<select :multiple="multiple"><slot></slot></select>`, 
    mounted() { 
     $(this.$el) 
      .val(this.value) 
      .chosen({ width: '100%' }) 
      .on("change", e => this.$emit('input', $(this.$el).val())) 
    }, 
    watch: { 
     value(val) { 
      $(this.$el).val(val).trigger('chosen:updated'); 
     } 
    }, 
    destroyed() { 
     $(this.$el).chosen('destroy'); 
    } 
}); 

그리고 이런 식으로 그것을 사용 : 이것은 내 뷰 지시자이다 최신 값으로 업데이트되지 않았습니다. 초기 값으로 유지됩니다.

어떻게이 문제를 해결할 수 있습니까?

편집 : 이것은 작동합니다. 이것이 올바른 방법이라고 생각하십니까?

Vue.component("chosen-select", { 
    data() { 
     return { observer: null } 
    }, 
    props: { 
     value: [String, Array], 
     multiple: Boolean 
    }, 
    template: `<select :multiple="multiple"><slot></slot></select>`, 
    mounted() { 
     // Create the observer (and what to do on changes...) 
     this.observer = new MutationObserver(function (mutations) { 
      $(this.$el).trigger("chosen:updated"); 
     }.bind(this)); 

     // Setup the observer 
     this.observer.observe(
      $(this.$el)[0], 
      { childList: true } 
     ); 
     $(this.$el) 
      .val(this.value) 
      .chosen({ width: '100%' }) 
      .on("change", e => this.$emit('input', $(this.$el).val())) 
    }, 
    watch: { 
     value(val) { 
      $(this.$el).val(val); 
     } 
    }, 
    destroyed() { 
     $(this.$el).chosen('destroy'); 
    } 
}); 

답변

1

v-if을 사용하여 렌더링 할 때까지이 문제를 해결하는 가장 쉬운 방법은 선택을 렌더링하지 않는 것입니다.

<chosen-select v-if="states && states.length > 0" v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID"> 

또한 구성 요소가 업데이트 될 때 chosen:updated 이벤트가 방출 될 수 있습니다.

updated(){ 
    $(this.$el).trigger("chosen:updated") 
}, 

여러 선택에 대해 작동하지만 하나의 선택에 대해서는 신비하지 않습니다.

+0

처음에는 업데이트 작업을 시도했지만 v- 모델의 속성이 변경 될 때마다 업데이트가 호출되므로 비효율적 일 수 있습니다 (변경 선택 발생). https://stackoverflow.com/questions/38148297/in-vue-js-can-a-component-detect-when-the-slot-content-changes에서 영감을 얻어 내 코드를 변경했습니다. 내 편집을 참조하십시오. 그게 뭔지 알려주세요. –

-1

상태를 동적으로 가져 오는 방법을 잘 모르겠지만 jQuery를 사용하여 가져 오는 방법을 모르는 경우 문제가 있다고 생각합니다. Vue가 아닌 것들 (예 : jQuery)이 아무 것도 변경하지 않으면 Vue는 알림을받지 않습니다. 그렇지 않은 경우에도 this은 jQuery와 Vue가 서로 어울리지 않는 이유를 파악할 가치가 있습니다. 동적으로 가져 오는 방법을 추가 할 수 있습니까? 또한, 꽤 좋은 선택 컨트롤을 가지고 있고 완전히 Vue에있는 Vuetify과 같은 Vue 프레임 워크를 사용해보십시오.

관련 문제