Issue
I want to create a div
in which to position multiple material design icons at random positions.
For Example like this:
This is something I made using jQuery, but now I want to make this in VueJS, and not with shapes but with multiple material design icons.
for (var i = 0; i < 10; i++) {
$('.main').append('<div class="box"></div>');
}
$( '.box' ).each(function( index ) {
$(this).css({
left : Math.random() * ($('.main').width() - $(this).width()),
top : Math.random() * ($('.main').height() - $(this).height())
});
});
.main {
width: 600px;
height: 400px;
background: #f0f0f0;
position: relative;
}
.box {
width: 20px;
height: 20px;
background: black;
border-radius: 50px;
position: absolute;
/* parent width - box width */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main"></div>
Solution
A solution using a single file component within a Vue CLI-generated project:
We can use Vue's list rendering to recreate your for
-loop. We add template refs on .main
and .box
to get element references for the calculations below:
<template>
<div ref="main" class="main">
<div ref="box" class="box" v-for="i in 10"></div>
</div>
</template>
From the element references, we use clientWidth
and clientHeight
to calculate the box dimensions upon mounting:
<script>
export default {
async mounted() {
// wait for $refs to be available
await this.$nextTick()
this.$refs.box.forEach(box => {
box.style.left = Math.random() * (this.$refs.main.clientWidth - box.clientWidth) + 'px'
box.style.top = Math.random() * (this.$refs.main.clientHeight - box.clientHeight) + 'px'
})
}
}
</script>
The original CSS can be copied into a <style>
block:
<style>
.main {
/* insert original .main styles here */
}
.box {
/* insert original .box styles here */
}
</style>
You could use the same steps above with SVG paths to load random Material Design icons. For instance, bind a <path>
to a random SVG path from @mdi/js
(a popular MDI library):
Create a data property (named
"icons"
), and initialize it with a random range of icons from@mdi/js
:import * as mdiIcons from '@mdi/js' function randomInt(min, max) { min = Math.ceil(min) max = Math.floor(max) return Math.floor(Math.random() * (max - min) + min) } function randomIcons(count) { const allIcons = Object.values(mdiIcons) const start = randomInt(0, allIcons.length - count) return allIcons.slice(start, start + count) } export default { data() { return { icons: randomIcons(10), } }, }
Replace the
<div ref="box">
from the earlier example with<svg ref="box">
. And inside the<svg>
, add<path :d="icons[i]" />
, which binds to the random icons we generated above.<template> <div ref="main" class="main"> <svg ref="box" class="box" v-for="i in 10"> <path :d="icons[i]">/> </svg> </div> </template>
Answered By - tony19
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.