Search code examples
vue.jsnuxt.jsbootstrap-5masonry

How to properly load Bootstrap5's Masonry into Nuxt?


I am trying to use the Masonry plugin with Bootstrap5 and NuxtJS. When I follow the example here https://getbootstrap.com/docs/5.0/examples/masonry/ and incorporate it into my own codesandbox, I notice that my demo is not in the correct masonry format. See the gaps? My sandbox

My example:

enter image description here

Bootstrap's example:

enter image description here

What do I need to do to get my demo into format shown on the Bootstrap Masonry example page?


Solution

  • I checked how to load the script from a CDN either globally or locally. It was working but at one condition: you needed to NOT start on the masonry page.
    Meaning that if you loaded the app on a specific page, then moved to the one with the masonry it was working. But not if you started on this specific page. So, a pretty subpar solution.

    This article was really helpful to understand how to wait until the CDN script is fully loaded: https://vueschool.io/articles/vuejs-tutorials/how-to-load-third-party-scripts-in-nuxt-js/

    Then I realized that we are far better installing it directly as an NPM dependency. Therefore, I proceeded to the masonry repo. Found a great message on how to setup the whole thing in Nuxt.

    And after a removal of some useless stuff and some modern dynamic import, here we are

    <template>
      <main>
        <h1>Bootstrap and Masonry</h1>
    
        <div class="row" id="masonry">
        <!-- ... -->
      </main>
    </template>
    
    <script>
    export default {
      async mounted() {
        if (process.browser) {
          let { default: Masonry } = await import('masonry-layout')
          new Masonry('#masonry', { percentPosition: true })
        }
      },
    }
    </script>
    

    The final solution is looking pretty well and there is not a lot of code. On top of that, the code is properly loaded. And you can load it on a click or any other event.