Отключить Swiper при щелчке по кнопке с $ emit («что-то») от дочернего компонента в Vue - PullRequest
0 голосов
/ 11 марта 2020

Я создаю приложение, используя Vue и Laravel. У меня есть гармошка, которая на мобильном телефоне становится слайдером Swiper (каждая переключаемая группа становится слайдом). Однако, когда пользователь переключает аккордеон, я хочу временно отключить смахивание, чтобы пользователь не мог пролистывать другие предметы, пока аккордеон открыт (он просто выглядит плохо, плюс не совсем соответствует тому, что было разработано). Я использую Vue компоненты. Ниже приведена упрощенная версия моего кода:

Аккордеон. vue

<template>
    <div class="swiper-slide">
        <!-- rest of the accordion omitted for brevity -->
        <button @click="toggle">Toggle</button>
    </div>
</template>

<script>
    export default {
        name: 'Accordion',
        data() {
            return {
                open: false
            }
        },
        methods: {
            toggle() {
                this.open = !this.open;
                // passing to parent
                this.$emit('toggled');
            },

        }
    }
</script>

Родительский

<template>
    <div class="accordion-wrap swiper-container">
        <div class="swiper-wrapper">
            <Accordion @toggled="disabledSwiping" />
        </div>
    </div>
</template>

<script>
    import Swiper from 'swiper';
    import Accordion from '@/js/components/Accordion';

    // create a breakpoint to watch the swiper and stop using it on desktop
    const breakpoint = window.matchMedia( '(min-width:1279px)' );

    export default {
        name: 'ReceivedReference',
        components: {
            Accordion
        },
        data() {
            return {
                mySwiper: undefined,
                options: {
                    speed: 400,
                    loop: false,
                    slidesPerView: 0,
                    spaceBetween: 0,
                    noSwiping: false,
                    noSwipingSelector: '.accordion-wrap',
                    breakpoints: {
                        320: {
                            slidesPerView: 1,
                            spaceBetween: 15,
                            noSwipingSelector: '.accordion-wrap',
                            noSwiping: false
                        }
                    }
                }
            }
        },
        methods: {
            breakpointChecker() {
                let mySwiper = this.mySwiper;

                if ( breakpoint.matches === true ) {
                    if ( mySwiper !== undefined ) mySwiper.update();
                    return;
                } else if ( breakpoint.matches === false ) {
                    return this.enableSwiper();
                }
            },
            enableSwiper() {
                let mySwiper = this.mySwiper;
                let options = this.options;
                mySwiper = new Swiper ('.accordion-wrap', options);
            },
            disabledSwiping() {
                // this updates on the Vue instance but doesn't disable swiping
                this.options['breakpoints'][320]['noSwiping'] = true;
            }
        },
        mounted () {
            this.breakpointChecker();
            breakpoint.addListener(this.breakpointChecker);


        }
    }
</script>

Как уже упоминалось, когда я проверял свои Vue инструменты разработки, свойство "noSwiping" меняется на true, но смахивание все еще включено. Если я добавлю true в качестве параметра по умолчанию, то есть

breakpoints: {
    320: {
        slidesPerView: 1,
        spaceBetween: 15,
        noSwipingSelector: '.accordion-wrap',
        noSwiping: true
    }
}

, он отключится, поэтому ясно, что может работать, но, похоже, он не реагирует? Не уверен, что я делаю неправильно, но был бы признателен за любые указатели.

Большое спасибо

...