source

vuejs는 상위 구성 요소에서 하위 구성 요소로 모델을 전달하고 변환을 허용합니다.

goodcode 2022. 8. 3. 23:12
반응형

vuejs는 상위 구성 요소에서 하위 구성 요소로 모델을 전달하고 변환을 허용합니다.

현재 가지고 있는 것은vue-multiselect필요한 컴포넌트v-model.

단일 선택 컴포넌트와 다중 선택 컴포넌트를 각각 작성할 수 있도록 이 컴포넌트를 랩합니다.

단일 선택 구성 요소 작업 중 다음 경고가 발생했습니다.

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "model"

맞는 말입니다만, 제 경우는 부모로부터의 값을 정말로 변경할 필요가 있습니다(싱글 셀렉트 코드를vue-multiselectcode) 컴포넌트 및 이 경고도 원하지 않습니다.

내 컴포넌트 코드는 다음과 같습니다.

Vue.component('single-select', {
    props: {
        model: {
            required: true
        }
    }
    template: '<multiselect\n' +
    '    v-model="model"\n' +
    ...>\n' +
    ...
    '</multiselect>'
});

하나의 솔루션은 함수를 모델 파라미터로 전달하고 부모로부터 필드를 반환하는 것이지만, 저는 더 나은 솔루션을 원합니다.

Vue에는 .sync 수식자라는 양방향 바인딩 바로 가기가 있습니다.

고객의 경우 작동 방식:

합격 시 .sync 추가model버팀목으로서

<single-select :model.sync="..."></single-select>

을 방출하다.update:model아이의 입력 이벤트에서

Vue.component('single-select', {
    props: {
        model: {
            required: true
        }
    },
    template: `<multiselect :value="model" @input="$emit('update:model', $event)"> </multiselect>`
});

그냥 내부만 줘model다른 이름을 참조하고 Vue 구성 요소의 데이터 기능에서 수동으로 매핑합니다.

Vue.component('single-select', {
    props: {
        model: {
            required: true
        }
    },
    data: function() {
        return {
            singleSelectModel: this.model
        };
    }
    template: '<multiselect v-model="singleSelectModel"></multiselect>';
});

이는 물론 부모 데이터를 변환하지 않고 단순히 복사하는 것을 전제로 하고 있습니다.model자녀 구성 요소가 원할 때 언제든지 변경할 수 있는 자유를 부여합니다.

자녀로부터 부모 데이터도 갱신하는 경우는, 자녀로부터 이벤트를 송신해, 부모로부터 수신하는 것을 검토해야 합니다.

언급URL : https://stackoverflow.com/questions/49943268/vuejs-pass-model-from-parent-component-to-children-component-and-allow-mutation

반응형