Programing

Vue 2 사용자 지정 선택2: @put이 작동하는 동안 @change가 작동하지 않는 이유

c10106 2022. 4. 26. 21:30
반응형

Vue 2 사용자 지정 선택2: @put이 작동하는 동안 @change가 작동하지 않는 이유

Vue 2에 대한 사용자 지정 select2 입력 요소를 생성했다.

제 질문은 왜 그럴까 입니다.

<select2 v-model="vacancy.staff_member_id" @input="update(vacancy)"></select2>

일하지만

<select2 v-model="vacancy.staff_member_id" @change="update(vacancy)"></select2>

아닌가?

정상 이후<input>Vue의 원소들은@change핸들러, 내 사용자 정의 select2 입력이 같다면 좋겠다.


사용자 지정 요소에 대한 일부 정보:

이 요소의 목적은 모든 것을 렌더링하지 않는 것이다.<option>요소들 그러나 오직 필요한 것들만, 왜냐하면 우리는 한 페이지에 많은 선택2 입력과 많은 선택사항들을 가지고 있기 때문에, 선택2 입력안에 페이지 로드가 느려지게 한다.

이 해결책은 그것을 훨씬 더 빨리 만든다.

Vue.component('select2', {
    props: ['options', 'value', 'placeholder', 'config', 'disabled'],
    template: '<select><slot></slot></select>',
    data: function() {
        return {
            newValue: null
        }
    },
    mounted: function () {

        var vm = this;

        $.fn.select2.amd.require([
            'select2/data/array',
            'select2/utils'
        ], function (ArrayData, Utils) {

            function CustomData ($element, options) {
                CustomData.__super__.constructor.call(this, $element, options);
            }

            Utils.Extend(CustomData, ArrayData);

            CustomData.prototype.query = function (params, callback) {

                if (params.term && params.term !== '') {
                    // search for term
                    var results;
                    var termLC = params.term.toLowerCase();
                    var length = termLC.length;

                    if (length < 3) {
                        // if only one or two characters, search for words in string that start with it
                        // the string starts with the term, or the term is used directly after a space
                        results = _.filter(vm.options, function(option){
                            return option.text.substr(0,length).toLowerCase() === termLC ||
                                _.includes(option.text.toLowerCase(), ' '+termLC.substr(0,2));
                        });
                    }

                    if (length > 2 || results.length < 2) {
                        // if more than two characters, or the previous search give less then 2 results
                        // look anywhere in the texts
                        results = _.filter(vm.options, function(option){
                            return _.includes(option.text.toLowerCase(), termLC);
                        });
                    }

                    callback({results: results});
                } else {
                    callback({results: vm.options}); // no search input -> return all options to scroll through
                }
            };

            var config = {
                // dataAdapter for displaying all options when opening the input
                // and for filtering when the user starts typing
                dataAdapter: CustomData,

                // only the selected value, needed for un-opened display
                // we are not using all options because that might become slow if we have many select2 inputs
                data:_.filter(vm.options, function(option){return option.id === parseInt(vm.value);}),

                placeholder:vm.placeholder
            };

            for (var attr in vm.config) {
                config[attr] = vm.config[attr];
            }

            if (vm.disabled) {
                config.disabled = vm.disabled;
            }

            if (vm.placeholder && vm.placeholder !== '') {
                $(vm.$el).append('<option></option>');
            }

            $(vm.$el)
            // init select2
                .select2(config)
                .val(vm.value)
                .trigger('change')
                // prevent dropdown to open when clicking the unselect-cross
                .on("select2:unselecting", function (e) {
                    $(this).val('').trigger('change');
                    e.preventDefault();
                })
                // emit event on change.
                .on('change', function () {
                    var newValue = $(this).val();
                    if (newValue !== null) {
                        Vue.nextTick(function(){
                            vm.$emit('input', newValue);
                        });
                    }
                })
        });

    },
    watch: {
        value: function (value, value2) {

            if (value === null) return;

            var isChanged = false;
            if (_.isArray(value)) {
                if (value.length !== value2.length) {
                    isChanged = true;
                } else {
                    for (var i=0; i<value.length; i++) {
                        if (value[i] !== value2[i]) {
                            isChanged = true;
                        }
                    }
                }
            } else {
                if (value !== value2) {
                    isChanged = true;
                }
            }

            if (isChanged) {

                var selectOptions = $(this.$el).find('option');
                var selectOptionsIds = _.map(selectOptions, 'value');

                if (! _.includes(selectOptionsIds, value)) {
                    var missingOption = _.find(this.options, {id: value});

                    var missingText = _.find(this.options, function(opt){
                        return opt.id === parseInt(value);
                    }).text;

                    $(this.$el).append('<option value='+value+'>'+missingText+'</option>');
                }

                // update value only if there is a real change
                // (without checking isSame, we enter a loop)
                $(this.$el).val(value).trigger('change');
            }
        }
    },
    destroyed: function () {
        $(this.$el).off().select2('destroy')
    }

그 이유는 구성 요소의 이벤트를 듣고 있기 때문이다.<select2>실제 DOM 노드가 아닌.구성 요소의 이벤트는 한정자를 사용하지 않는내부에서 방출되는 사용자 지정 이벤트를 가리킨다.

사용자 지정 이벤트는 기본 DOM 이벤트와 다름: DOM 트리를 거품이 일지 않으며, 해당 이벤트를 사용하지 않는 한 캡처할 수 없음.native수식어문서에서:

Vue의 이벤트 시스템은 브라우저의 EventTarget API와는 별개라는 점에 유의하십시오.그들은 비슷한 방식으로 일하지만,$on그리고$emitaddEventListener 및 dispatchEvent에 대한 별칭이 아님.

게시한 코드를 들여다보면 끝부분에 다음과 같은 내용이 나온다.

Vue.nextTick(function(){
    vm.$emit('input', newValue);
});

이 코드는 사용자 지정 이벤트를 발생함inputVueJS 이벤트 네임스페이스로, 기본 DOM 이벤트가 아님.이 이벤트는 다음에 의해 캡처됨v-on:input또는@input당신 앞으로<select2>VueJS 구성 요소.반대로, 아니니까change이벤트를 내보내는 방법vm.$emit, 바인딩v-on:change절대 해고되지 않을 것이고 따라서 당신이 관찰한 비행동도 없을 것이다.

테리가 그 이유를 지적했지만, 사실 당신은 간단히 당신의 의견을 전달할 수 있다.update어린이 구성 요소에 대한 이벤트.아래의 데모를 확인하십시오.

Vue.component('select2', {
  template: '<select @change="change"><option value="value1">Value 1</option><option value="value2">Value 2</option></select>',
  props: [ 'change' ]
})

new Vue({
  el: '#app',
  methods: {
    onChange() {
    	console.log('on change');
    }
  }
});
<script src="https://unpkg.com/vue@2.4.2/dist/vue.min.js"></script>
<div id="app">
  <div>
    <p>custom select</p>
    <select2 :change="onChange"></select2>
  </div>
  <div>
    <p>default select</p>
    <select @change="onChange">
      <option value="value1">Value 1</option>
      <option value="value2">Value 2</option>
    </select>
  </div>
</div>

만지작거리다

참조URL: https://stackoverflow.com/questions/45670145/vue-2-custom-select2-why-is-change-not-working-while-input-is-working

반응형