Прослушивание событий от родительских компонентов в VueJs - PullRequest
0 голосов
/ 11 января 2020

Концепция состоит в том, чтобы отображать изображение в модальном режиме (дочерний компонент), когда пользователи нажимают на определенное изображение из коллекции (родительский компонент). Это мой код:

маршруты. js

import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import Explore from './components/Explore';
import OeModal from './components/OeModal';

export default {
    mode: 'history',

    routes: [
        {
            path: '/',
            component: Home
        },
        {
            path: '/about',
            component: About
        },
        {
            path: '/contact',
            component: Contact
        },
        {
            path: '/explore/',
            component: Explore,

            children: [
                { path: ':id', component: OeModal, name: 'OeModal', props: true }
              ]
        },
    ]
};

Explore. vue (родительский)

<template>
    <div class="" id="rbGallery">

        <div v-masonry transition-duration="0.3s" item-selector=".item"  origin-top="true" class="flex">
            <div v-masonry-tile class="item w-1/4" v-for="(img, index) in photos">
                <a :href="'/explore/' + img.id" @click.prevent="imgModal(img.id)"><img class="" :src="img.url" alt="Card image cap"></a>
            </div>
        </div>

        <router-view></router-view>

    </div>
</template>

<script>

    export default {

        computed: {
            photos() {
                return this.$store.getters['photos/imgData'];
            }
        },

        methods: {

            imgModal(id) {
                this.$emit('imgClicked', id);

                this.$router.push({ name: 'OeModal', params: {id: id}})
            }
        }
    }
</script>

и OeModal. vue (дочерний )

<template>
    <div>

        <oe-modal name="testModal" width="80%" height="auto" :scrollable="true">

            <div class="px-16 py-8">

                <img class="modalImg" :src="img.url" alt="Sunset in the mountains">

                <div class="text-center m-auto">
                    <span class="inline-block bg-grey-lighter rounded-full px-3 py-1 text-sm font-semibold text-grey-darker mr-2">#photography</span>
                    <span class="inline-block bg-grey-lighter rounded-full px-3 py-1 text-sm font-semibold text-grey-darker mr-2">#travel</span>
                    <span class="inline-block bg-grey-lighter rounded-full px-3 py-1 text-sm font-semibold text-grey-darker">#winter</span>
                </div>

                <div>
                    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Accusantium animi hic obcaecati neque dolores praesentium perspiciatis sit ea similique, quae tempora in saepe mollitia odio iusto deleniti harum? Quis, in reiciendis fugiat cum corrupti libero m
                        inus sequi asperiores iusto provident fugit tenetur repellendus nisi! Cupiditate magni unde obcaecati nemo exercitationem.</p>
                </div>
            </div>

        </oe-modal>

    </div>
</template>

<script>
    export default {

        data() {
            return {
            }
        },

        created() {
            this.$parent.$on('imgClicked', this.$modal.show('testModal'));
        },

        watch: {
            '$route': function(to, from) {
                // this.$modal.show('testModal');
            },
        },

        computed: {
            img() {
                return this.$store.getters['photos/imgData'].find(i => i.id == this.$route.params.id);
            }
        },

        methods: {
            show () {
                this.$modal.show('testModal');
            },
            hide () {
                this.$modal.hide('hello-world');
            }
        }
    }
</script>

Как видите, я установил событие imgModal из родительского компонента, чтобы оно запускалось при каждом нажатии на изображение. Я попытался прослушать событие от OeModal (дочерний компонент) и выполнить там некоторую работу, но я просто не могу заставить его работать. При попытке this.$parent.$on('imgClicked', this.$modal.show('testModal')); в консоли я получил следующую ошибку:

[Vue warn]: Error in event handler for "imgClicked": "TypeError: Cannot read property 'apply' of undefined"

1 Ответ

0 голосов
/ 11 января 2020

Похоже, что вы излучаете событие до создания компонента и регистрируетесь для прослушивания события. Итак, вместо этого:

this.$emit('imgClicked', id);
this.$router.push({ name: 'OeModal', params: {id: id}})

попробуйте это:

this.$router.push({ name: 'OeModal', params: {id: id}})
this.$emit('imgClicked', id);

или, возможно,:

this.$router.push({ name: 'OeModal', params: {id: id}})
this.$nextTick(function () {
    this.$emit('imgClicked', id);
});

Кроме того, неправильная процедура регистрации обработчика событий , Вместо этого:

this.$parent.$on('imgClicked', this.$modal.show('testModal'));

попробуйте это:

this.$parent.$on('imgClicked', function () { this.$modal.show('testModal'); });
...