Add toggle to VueJS SPA with Bulma

When staring new Vue project and create navigation often have problems with navigation configuration for cross device.

This year I prefer to use Bulma CSS framework in frontend projects.

For example this code. Demo you can see — here.

Setup Bulma

Install to project

npm install bulma

or

 yarn add bulma

Add Bulma import to the App.vue file <style>

 &lt;style lang="scss">
  @import 'bulma/bulma.sass';
...

Setup Sass

npm install node-sass sass-loader --save-dev

or

yarn add node-sass sass-loader -D

Add navigation

&lt;nav
      class="navbar"
      role="navigation"
      aria-label="main navigation"
    >
      &lt;div class="navbar-brand">
        &lt;div class="navbar-item">
          Bulls and cows
        &lt;/div>
        &lt;a
          role="button"
          class="navbar-burger"
          data-target="navMenu"
          aria-label="menu"
          aria-expanded="false"
          @click="openNavigation"
        >
          &lt;span aria-hidden="true" />
          &lt;span aria-hidden="true" />
          &lt;span aria-hidden="true" />
        &lt;/a>
      &lt;/div>
      &lt;div
        :class="{'navbar-menu': true, 'is-active': navigationMain }"
        id="navMenu"
      >
        &lt;div class="navbar-start">
          &lt;router-link
            to="/"
            class="navbar-item is-active"
          >
            Home
          &lt;/router-link
        &lt;/div>
        &lt;div class="navbar-end">
          &lt;router-link
            to="/about"
            class="navbar-item"
          >
            About
          &lt;/router-link>
          &lt;router-link
            to="/rules"
            class="navbar-item"
          >
            Rules
          &lt;/router-link>
        &lt;/div>
      &lt;/div>
    &lt;/nav>

Add to data section variable

navigationMain: false

Create method to toggle active class (then click on burger icon)

openNavigation() {
   this.navigationMain = !this.navigationMain;
}

Add watcher for route changes (to set false navigationMain )

watch: {
  $route(to, from) {
    this.navigationMain = false;
  }
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.