[Vuejs]-How do I dynamically show a mobile menu with Tailwind and Vue.js?

1👍

you can write a plugin for it in you app and import it, im using nuxt and this worked for me

export default (context, inject) => {
  const burger = () => {
    const menu = document.querySelector("#menu");

    if (menu.classList.contains("hidden")) {
      menu.classList.remove("hidden");
    } else {
      menu.classList.add("hidden");
    }
  };
  inject("burger", burger);
  context.$burger = burger;
};

-1👍

One way of achieving this could be to configure the TailwindCSS-breakpoints in your tailwind.config.js and to then reuse that file to import the breakpoint-values into your Menu-component.

Here we are setting TailwindCSS breakpoints according to the TailwindCSS documentation. We are actually just setting the default TailwindCSS breakpoint values, but setting them makes them accessible via the file.

//tailwind.config.js

module.exports = {
  theme: {
    screens: {
      sm: '640px',
      md: '768px',
      lg: '1024px',
      xl: '1280px'
    }
  }
}

Now, in your Menu.vue, you can import the breakpoint from your TailwindCSS-config and write the necessary function, to check if the current window-size is smaller than the md-breakpoint. If it’s not, you can simply return true. If it is, you can check, if the menu was toggled open.

// Menu.vue
<script>
const tailwindConfig = require('tailwind.config.js')

export default {
  data() {
    return {
      windowWidth: 0,
      menuOpen: false,
      mdBreakpoint: Number(tailwindConfig.theme.screens.md.replace('px', ''))
    }
  },
  computed: {
    menuVisible() {
      return this.windowWidth > mdBreakpoint ? true : this.menuOpen

    }
  },
  methods: {
    updateWindowSize() {
      this.windowWidth = window.innerWidth
    },
    clickMenu() {
      this.menuOpen = !this.menuOpen
    }
  },
  mounted() {
    this.updateWindowSize()
    window.addEventListener('resize', this.updateWindowSize)
  },
  beforeDestroyed() {
    window.removeEventListener('resize', this.updateWindowSize)
  }
}
</script>

Leave a comment