Search code examples
cssvue.jsnuxt.jsbulma

How to set has-navbar-fixed-top property only on some elements in Vue using Bulma?


I have a custom navigation bar made with Bulma and I am using Nuxt.js for creating my application. The problem is that I want to have navbar fixed on top but only on some of my views. For example, I want to have navigation on my index page and all of the other pages connected to the index, but I don't want to have it on my log-in and registration pages.

In Bulma docs it says:

Add the corresponding has-navbar-fixed-top or has-navbar-fixed-bottom modifier to either <html> or <body> element to provide the appropriate padding to the page

If I do that in my app.html file all of my views will have padding on top. Is there a way to overwrite has-navbar-fixed-top property to unset it on views that don't need it? Or can I somehow only set it for the components/pages that should have it?


Solution

  • All you need to do is make an array full of your paths (pagesWithNavBar) and a computed method (shouldHaveNavBar) that returns true or false based on if the current path in url matches any item from our array (pagesWithNavBar) and finally add a check in the head method that checks if we currently are on the page with path included in our array!

    .vue file - most likely your layout -> script tag

    export default {
        data() {
          return {
            pagesWithNavBar: [
              "/login", "/signup" // add here all your paths where u wish to have your navbar
            ] 
          } 
        },
        computed: {
          shouldHaveNavBar() {
            return this.pagesWithNavBar.includes(this.$route.path)
          }
        },
        head() { // since nuxt.js uses vue-meta to update the document head and meta attributes 
                 // you can also use it for your own good which means adding meta tags or editing
                 // the attributes of a body tag! you can learn more here
                 // https://nuxtjs.org/guide/views/#html-head
                 // or here
                 // https://github.com/declandewet/vue-meta#recognized-metainfo-properties
          return { 
            bodyAttrs: { 
              class: this.shouldHaveNavBar ? "has-navbar-fixed-top" : ""
            }
          }
        }
    }