Vueと共にJquery Chosenを使用しています。Vue指示が値を更新しない - Jquery Chosen
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ディレクティブで
<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", {
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');
}
});
私は当初、更新されたものを試しましたが、v-modelの属性が変更されるたびに更新が呼び出されるため、非効率的である可能性があります(変更が発生しました)。 https://stackoverflow.com/questions/38148297/in-vue-js-can-a-component-detect-when-the-slot-content-changesからインスピレーションを得て、それに応じてコードを変更しました。私の編集を参照してください。それがどういうものか教えてください。 –