vue.jsresponsivebuefy

How to dynamic set element's class depending on Buefy breakpoint


So I have been using Buefy as an UI library for this new project and I come from a Vuetify background.

What I want to achieve using Buefy is this:

<div
  :class="{
    'ml-2': (condition to apply the class to mobile breakpoint)
  }"
>
...

In Vuetify I'd write the code like this:

<div
  :class="{
    'ml-2': $vuetify.breakpoint.mobile,
  }"
>
...

Is there an equivalent solution in Buefy?


Solution

  • I checked Buefy's docs and it doesn't seem to have breakpoints feature.

    You can instead do it yourself manually by creating a plugin or just add the following in your component:

    <script>
    export default {
      data() {
        return {
          isMobile: false,
        }
      },
    
      mounted() {
        const mediaQuery = window.matchMedia('(min-width: 1024px)');
    
        // Set initial value on first load.
        this.isMobile = !mediaQuery.matches
    
        // Listen for changes
        mediaQuery.addEventListener('change', event => {
          if (event.matches) {
            console.log('>= 1024px');
            this.isMobile = false;
          } else {
            console.log('< 1024px');
            this.isMobile = true;
          }
        })
      }
    }
    </script>