有没有办法在Vue.js中动态插入点击事件?

时间:2018-06-04 20:19:29

标签: javascript vue.js vuejs2 lifecycle

尝试仅根据移动视口在元素上插入一些计算方法。以下是我正在使用的基本要点:

<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>

我想尝试使用resize事件来确定浏览器宽度,以便我可以将计算出的函数动态插入到<a>标记

2 个答案:

答案 0 :(得分:2)

你可以提供两个不同的元素(一个用于桌面,另一个用于移动),如Karthikeyan所述,或有条件地将click事件添加到该元素:

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

答案 1 :(得分:1)

您可以添加一个数据,说明该视图是否可移动,并使用v-if,v-else并将@click仅添加到v-if =&#34; isMobileView&#34;

<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>