IT이야기

$emit를 동기식 모드로 실행하고 excast 이벤트에서 결과를 다시 얻을 수 있는가?

cyworld 2022. 5. 5. 10:17
반응형

$emit를 동기식 모드로 실행하고 excast 이벤트에서 결과를 다시 얻을 수 있는가?

동기식 방출로 실행이 가능하고 그 결과를 호출 방식 자체에서 다시 얻을 수 있는가.그래서 나는 $emit이 완료된 후 다음 문장을 실행하고자 한다.다음과 같다.

Parent component has method, 
                 doCustomValidation();

child component is as follow:
methods:
{
  Save: function(){
 // Can I get the response here from parent component and then, execute 
    doGenericValidation ?

 var errorFields = this.$emit('custom-validation');  
   doGenericValidation(errorFields);   //this is generic validations
}

이것을 동기식으로 만들려고 해서는 안 된다.대신 다음과 같은 아이디어를 사용할 수 있을 것이다.

methods: {
    myMethod() {
        // Pass a function as a parameter.
        this.$emit('custom-validation', this.onComplete);
    },
    onComplete() {
        // Do stuff after custom-validation has completed.
    }
}

그런 다음 이벤트를 사용하는 구성 요소:

<some-component @custom-validation="doStuff" />
<script>
...
methods: {
    doStuff(done) {
        // Your logic here. After that, call the callback function.
        done();
    }
}
...

배출에 대한 약속 기반 포장지를 만들고 결과를 기다릴 수 있다.

다음은 내 프로젝트를 위해 만든 꽤 일반적인 솔루션이다.

    async emitPromised(method, ...params){
        let listener = this.$listeners[method] || this.$attrs[method] || this[method]
        if(listener){
            let res = await listener(...params)
            return res === undefined || res
        }
        return false
    },

이제 이렇게 사용할 수 있다.

        async onDelete(){
            this.isDeleting = true
            let res = await this.emitPromised("delete")
            this.isDeleting = false
            if(res){
                this.closeConfirm()
            }
        },

혼합을 통해 이 방법을 포함하거나 Vue 인스턴스에 전체적으로 연결하여 모든 구성 요소가 액세스할 수 있도록 하십시오.

참고로,$listeners이 구성 요소에 바인딩된 모든 메서드 저장@또는v-on(좋다)<MyComponet @click="onClick"/>) 동안$attrs다음을 사용하여 구성 요소에 전달된 모든 내용을 저장하십시오.v-bind또는:(좋다)<MyComponet :click="onClick"/>)

아니요.$emit항상 대기열에 있을 것이다.또한 다수의 청취자가 있을 수 있기 때문에, 반환 값은 정말로 이치에 맞지 않는다.

해결책으로, 당신은 함수를 속성으로 보낸 다음, 그것을 직접 호출할 수 있다.

참조URL: https://stackoverflow.com/questions/55364122/is-it-possible-to-execute-emit-as-synchronous-mode-and-get-the-result-back-from

반응형