Rewrite the title: Emit Vue.js events based on screen width
P粉463291248
P粉463291248 2024-03-28 10:37:34
0
1
465

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>

P粉463291248
P粉463291248

reply all(1)
P粉216203545

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:

sssccc

Or create a calculated variable to define whether the width is below the threshold:

sssccc

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template