Categories
JavaScript Vue

Create a Photo Grid in a Vue App with the vue-masonry Package

Spread the love

To make a page that displays images like Google Image or Flickr in a Vue app, we can use the vue-masonry package.

We can install it by running:

npm install vue-masonry --save

Then we can use it adding the following to main.js:

import Vue from "vue";
import App from "./App.vue";
import { VueMasonryPlugin } from "vue-masonry";

Vue.use(VueMasonryPlugin);

Vue.config.productionTip = false;
new Vue({
  render: h => h(App)
}).$mount("#app");

We register the plugin globally by using the Vue.use method.

Then we can use it by adding the following to our component:

<template>
  <div id="app">
    <div v-masonry transition-duration="0.3s" item-selector=".item">
      <div
        class="item"
        v-masonry-tile
        :key="index"
        :fit-width="true"
        :horizontal-order="true"
        v-for="(item, index) in blocks"
      >
        <img :src="item">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      blocks: Array(50)
        .fill()
        .map(() => {
          const size = 100 + Math.floor(Math.random() * 100);
          return `https://placekitten.com/g/200/${size}`;
        })
    };
  }
};
</script>

<style>
.item {
  width: 200px;
  margin: 3px;
}
</style>

We add the images by using the Place Kitten with the width and the height of the image we want to get in the path.

Also, we styled our type by using the item class to set the width and the margin.

Then in the template, we use the v-masonry directive.

We set the transition-duration to set the duration of the animation when tiles load.

The item-selector is used to set the selector of each tile.

We set it to the item class so that we can style our masonry tiles.

Inside the outer div, we have another div with the v-masonry-tile directive.

We have the fit-width option to set the width of the container.

horizontal-order lets us lay out the items to maintain left to right order.

Inside the div, we have the img tag to display the actual image in the tile.

Now we get a responsive masonry grid that displays cat pictures.

The images will rearrange to fit the screen if we resize the screen.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.