[Vuejs]-Random positioned icons in a div with VueJS

1๐Ÿ‘

โœ…

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>

demo 1

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):

  1. 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),
        }
      },
    }
    
  2. 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>
    

demo 2

Leave a comment