programing

상위 구성 요소에서 하위 구성 요소로의 이벤트

minecode 2023. 1. 14. 09:44
반응형

상위 구성 요소에서 하위 구성 요소로의 이벤트

부모 컴포넌트에서 생성된 이벤트가 있으며 자녀는 이에 반응해야 합니다.에서는 이 방법이 권장되지 않는 것을 알고 있습니다.vuejs2그리고 나는 그것을 해야 한다.$root방출이 꽤 심해요그래서 제 암호는 이렇습니다.

<template>
    <search></search>
    <table class="table table-condensed table-hover table-striped" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
        <tbody id="trans-table">
            <tr v-for="transaction in transactions" v-model="transactions">
                <td v-for="item in transaction" v-html="item"></td>
            </tr>
        </tbody>
    </table>
</template>

<script>
    import Search from './Search.vue';

    export default {
        components: {
            Search
        },
        data() {
            return { 
                transactions: [], 
                currentPosition: 0 
            }
        },
        methods: {
            loadMore() {
                this.$root.$emit('loadMore', {
                    currentPosition: this.currentPosition
                });
            }
        }
    }
</script>

당신이 볼 수 있듯이.loadMore무한 스크롤 시 트리거되며 이벤트가 하위 구성 요소 검색으로 전송됩니다.검색뿐만 아니라 뿌리가 있기 때문에 모두에게 방송되고 있습니다.

이를 위해 무엇이 더 나은 접근법인가.소품을 사용해야 한다는 건 알지만 어떻게 해야 할지 모르겠어요.

변수만 있으면 된다(이것을 말한다).moreLoaded)는, 매회 증가합니다.loadMore호출됩니다.그거 건네주고currentPosition고객님께search컴포넌트입니다.검색에서 다음을 수행할 수 있습니다.watch moreLoaded적절한 조치를 취할 수 있습니다.

갱신하다
해키? 해결책?아니, 절대!;)

현지화된 이벤트 버스를 사용할 수도 있습니다.다음과 같이 설정합니다.

export default {
    components: {
        Search
    },
    data() {
        return {
            bus: new Vue(),
            transactions: [], 
            currentPosition: 0 
        }
    },
    methods: {
        loadMore() {
            this.bus.$emit('loadMore', {
                currentPosition: this.currentPosition
            });
        }
    }
}

검색으로 전달합니다.

<search :bus="bus"></search>

어느쪽이든bus(물론) 받침대로서, 그리고 같은 단면을 가지고 있다.

created() {
    this.bus.$on('loadMore', (args) => {
        // do something with args.currentPosition
    });
}

@tobias는@Roy J의 답변에 대한 Bora의 코멘트는 매우 중요합니다.컴포넌트가 여러 번 생성 및 파기된 경우(사용 시 등)v-if)는 핸들러를 여러 번 호출하는 것으로 종료됩니다.또, 컴포넌트가 파괴되어도(매우 불량한 경우도 있습니다) 핸들러가 호출됩니다.

@tobiasBora의 설명에 따르면 Vue의$off()기능.이벤트 핸들러 함수에 대한 참조가 필요했기 때문에 이것은 사소한 일이 아닙니다.결과적으로 이 핸들러를 컴포넌트 데이터의 일부로 정의하게 되었습니다.이것은 화살표 기능이어야 합니다.그렇지 않으면,.bind(this)기능 정의 후를 선택합니다.

export default {
    data() {
        return {
            eventHandler: (eventArgs) => {
                this.doSomething();
            }
        }
    },
    methods: {
        doSomething() {
            // Actually do something
        }
    },
    created() {
        this.bus.$on("eventName", this.eventHandler);
    },
    beforeDestroy() {
        this.bus.$off("eventName", this.eventHandler);
    },
}

언급URL : https://stackoverflow.com/questions/43256978/event-from-parent-to-child-component

반응형