A unique approach utilizing a single file component within a Vue CLI project:
To replicate your traditional for
-loop, we leverage Vue's list rendering. By assigning template refs to elements like .main
and .box
, we obtain references necessary for the calculations below:
<template>
<div ref="main" class="main">
<div ref="box" class="box" v-for="i in 10"></div>
</div>
</template>
Using these element references, we utilize clientWidth
and clientHeight
to derive box dimensions upon mounting:
<script>
export default {
async mounted() {
// ensure $refs are ready
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>
You may simply copy the original CSS into a <style>
block:
<style>
.main {
/* include original .main styles here */
}
.box {
/* include original .box styles here */
}
</style>
demo 1
For a creative twist, follow similar steps using SVG paths to display random Material Design icons. For example, bind a <path>
to a randomly selected SVG path from @mdi/js
(based on MDI library):
Set up a data property named "icons"
and populate it with a range of random icons sourced 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),
}
},
}
Substitute <div ref="box">
from the previous example with <svg ref="box">
. Inside the <svg>
, add
<path :d="icons[i]" />
to bind to the generated random icons.
<template>
<div ref="main" class="main">
<svg ref="box" class="box" v-for="i in 10">
<path :d="icons[i]">/>
</svg>
</div>
</template>
demo 2