I got the following code from the sidebar. When any link is clicked, I also emit an event to the root component and then call a function to hide the sidebar. This is working fine, but now I want the event to be emitted only when the screen width is less than 768px so that the event can only be emitted when I want the function to be called.
<div class="side-links"> <ul> <li> <router-link @click="$emit('navLinkClicked')" :to="{ name: 'Home' }" >Home</router-link > </li> <li> <router-link @click="$emit('navLinkClicked')" :to="{ name: 'Blog' }" >Blog</router-link > </li> <li> <router-link @click="$emit('navLinkClicked')" :to="{ name: 'About' }" >About</router-link > </li> </ul> </div>
You can use
window.innerWidth
to check the width of the current viewport. However, a global scope variable is not available in templates because its scope is limited to your component. You can create a handler method:Or create a calculated variable to define whether the width is below the threshold:
Personally I would choose the first option so you only have to check it once.
In Vue 2, it is also recommended to use the kebab-case event name.