programing

Vue.js에서 클릭 이벤트를 동적으로 삽입할 수 있는 방법이 있는가?

prostudy 2022. 4. 22. 20:55
반응형

Vue.js에서 클릭 이벤트를 동적으로 삽입할 수 있는 방법이 있는가?

모바일 뷰포트에만 의존하는 요소에 일부 계산 방법을 삽입하는 것을 목표로 한다.여기 내가 작업하고 있는 것의 기본적인 요지가 있다.

<a class="nav-link float-left p-x-y-16" v-bind:class={active:isCurrentTopicId(t.id)} @click="onTopicClicked($event, m, t)" href="#">{{t.title}}</a>

<script>

export default {
    data() {
        return {
            isClosed: false
        }
    },
    computed: {
        toggleMenu() {
            return {
                isClosed: this.isClosed
            }
        }
    },
    watch: {
        browserWidth(prevWidth, newWidth) {
            console.log('width changed from ' + newWidth + ' to ' + prevWidth);
    },
    mounted() {
        var that = this;
        this.$nextTick(function() {
            window.addEventListener('resize', function(e) {
                that.browserWidth = window.innerWidth;
                if(that.browserWidth > 824) {
                    console.log('Desktop View');
                } else {
                    console.log('Mobile View');
                }
            })
        })
    }
}
</script>

계산된 기능을 동적으로 삽입할 수 있도록 크기 조정 이벤트를 사용하여 브라우저 너비를 결정하려고 함<a>꼬리표를 달다

Karthikeyan이 명시한 두 가지 요소(데스크톱용 하나와 모바일용 하나)를 제공하거나 클릭 이벤트를 조건부로 해당 요소에 추가할 수 있다.

v-on="isMobileView ? { mouseover: onTopicClicked($event, m, t) } : {}"

보기가 모바일인지 아닌지를 나타내는 데이터를 추가하고 v-if , v-else 및 @click만 v-if="isMobileView"에만 추가되도록 할 수 있다.

<a v-if="isMobileView" class="nav-link float-left p-x-y-16" v-bind:class={active:isCurrentTopicId(t.id)} @click="onTopicClicked($event, m, t)" href="#">{{t.title}}</a>

<a v-else class="nav-link float-left p-x-y-16" v-bind:class={active:isCurrentTopicId(t.id)} href="#">{{t.title}}</a>

<script>

export default {
    data() {
        return {
            isClosed: false,
            isMobileView: false
        }
    },
    computed: {
        toggleMenu() {
            return {
                isClosed: this.isClosed
            }
        }
    },
    watch: {
        browserWidth(prevWidth, newWidth) {
            console.log('width changed from ' + newWidth + ' to ' + prevWidth);
    },
    mounted() {
        var that = this;
        function checkIfMobileView() {
            that.isMobileView = window.innerWidth <= 824;
        }
        this.$nextTick(function() {
            window.addEventListener('resize', checkIfMobileView);
        });
        checkIfMobileView();
    }
}
</script>

참조URL: https://stackoverflow.com/questions/50688176/is-there-a-way-to-dynamically-insert-click-events-in-vue-js

반응형