We can add a photo grid easily to a Vue app easily with the vue-masonry plugin.
In this article, we’ll look at how to add photo tiles with it.
Installation
We can install it by running:
npm install vue-masonry --save
or add it with a script
tag:
<script src="https://unpkg.com/vue-masonry@0.11.3/dist/vue-masonry-plugin-window.js"></script>
If we install the package, then we register the plugin by writing:
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");
in main.js
.
If we add the script
tag, then we write:
var VueMasonryPlugin = window["vue-masonry-plugin"].VueMasonryPlugin
Vue.use(VueMasonryPlugin)
to register it.
Usage
Once we did that, we write:
<template>
<div id="app">
<div v-masonry transition-duration="0.3s" item-selector=".item">
<div v-masonry-tile class="item" v-for="n in 100" :key="n">
<img :src="`https://picsum.photos/id/${n}/200/300`">
</div>
</div>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
to add the photo grid.
The v-masonry-tile
makes the div a tile.
v-masonry
makes an element the container for the photo grid.
transition-duration
is how long a transition runs.
item-selector
has the DOM item selector for the list element.
Other props includes column-width
for setting the column width with a number.
origin-left
sets the group elements to the right instead of the left if it’s false
.
origin-top
sets the group elements to the bottom instead of the top if it’s false
.
stamp
specifies which elements are stamped with the layout.
fit-width
sets the width of the container to fit the available number of columns.
stagger
sets the duration to stagger the item transition so items transition incrementally one after the other.
For example, we can write:
stagger="0.03s"
to set it.
destroy-detail
is the duration in milliseconds to wait before unloading the masonry tiles via masonry.destroy()
.
We can also trigger redraw manually with the this.$redrawVueMasonry(‘containerId’)
method.
containerId
is the ID of the block where we want to trigger the redraw.
Conclusion
We can add a photo masonry grid to a Vue app easily with the vue-masonry package.