4👍
✅
You can use window.innerWidth
to check the width of the current viewport. Global scope variables however is not available in the template, because its scoped to your component. You can either create a handler method:
<script>
methods: {
onNavLinkClicked() {
if (window.innerWidth < 768) {
this.$emit('navLinkClicked')
}
}
}
</script>
<template>
<div class="side-links">
<ul>
<li>
<router-link
@click="onNavLinkClicked"
:to="{ name: 'Home' }"
>
Home
</router-link
</li>
</ul>
</div>
</template>
or create a computed variable that defines if the width is below the treshold:
<script>
computed: {
isMobile() {
return window.innerWidth < 768;
}
}
</script>
<template>
<div class="side-links">
<ul>
<li>
<router-link
@click="isMobile ? $emit('navLinkClicked') : null"
:to="{ name: 'Home' }"
>
Home
</router-link
</li>
</ul>
</div>
</template>
Personally i’d go with the first option, so you’ll only have to do the check once.
In Vue 2 it is also recommended to use kebab-case for event names.
👤Lars
Source:stackexchange.com