Currently, I am working on a project using Laravel, VueJS, and the Masonry.js library to develop a dynamic gallery. However, I have encountered a peculiar issue.
Here is a snippet of my VueJS template:
<template lang="html">
<div id="uploads-grid">
<div class="grid" ref="grid">
<!-- GRID START -->
<div class="grid-item white-outline" v-for="(bg, index) in bgs" :style="'width:' + wd + 'px;height:' + hg[index] + 'px;'">
<img :src="'/storage/users/1/photos/1/' + bg.photo" :width="wd" :height="hg[index]">
</div>
<!-- GRID END -->
</div>
</div>
</template>
Here is how I retrieve the images:
<script>
import Masonry from 'masonry-layout';
export default {
data() {
return {
bgs: [],
wd: '300',
hg: []
}
},
methods: {
getPhotos() {
var url = '/photos/get'
axios.get(url).then(r => {
this.bgs = r.data
for (var i = 0; i < r.data.length; i++) {
var factor = r.data[i].width / 300
var resizeHeight = Math.floor(r.data[i].height / factor)
this.hg.push(resizeHeight)
}
});
}
},
mounted() {
let $masonry = new Masonry(this.$refs.grid, {
itemSelector: '.grid-item',
columnWidth: 300,
isFitWidth: true
});
},
created() {
this.getPhotos()
}
}
</script>
The issue at hand is that each image appears below the previous one.
In contrast, the following code snippet functions correctly:
<template lang="html">
<div id="uploads-grid">
<div class="grid" ref="grid">
<!-- GRID START -->
<div class="grid-item white-outline" v-for="(bg, index) in bgs" :style="'width:' + wd[index] + 'px;height:' + hg[index] + 'px;'">
<img :src="bg">
</div>
<!-- GRID END -->
</div>
</div>
</template>
<script>
import Masonry from 'masonry-layout';
export default {
data() {
return {
bgs: [],
wd: [],
hg: []
}
},
methods: {
rndBg() {
for (var i = 0; i < 20; i++) {
var wd = 300
var hg = Math.floor(Math.random() * 350) + 150
var bgsrc = 'https://placehold.it/' + wd + 'x' + hg
this.bgs.push(bgsrc)
this.wd.push(wd)
this.hg.push(hg)
}
}
},
mounted() {
let $masonry = new Masonry(this.$refs.grid, {
itemSelector: '.grid-item',
columnWidth: 300,
isFitWidth: true
});
},
created() {
this.rndBg()
}
}
</script>
However, as you can see, I am using placeholder dummy images instead of the ones I intended to use. Therefore, it does not suit my requirements. Despite using the same logic, it seems that I cannot resolve this issue.