Home  >  Q&A  >  body text

Rewrite the title: Emit Vue.js events based on screen width

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粉463291248P粉463291248205 days ago414

reply all(1)I'll reply

  • P粉216203545

    P粉2162035452024-03-29 09:58:51

    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.

    reply
    0
  • Cancelreply