Home > database >  How to emit event in Vue.js depending on the width of the screen
How to emit event in Vue.js depending on the width of the screen

Time:05-05

I've got the following code from my sidebar. When any link is clicked, I'm also emitting an event to my root component and then invoking a function to hide the sidebar. This is working well but now I would like the event to be emitted only when the width of the screen is less than 768px so that I can emit the event only when I want to invoke the function.

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

CodePudding user response:

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

Vue also recommends using kebab-case for event names.

  • Related