在Vue CLI生成的项目中使用单个文件组件的解决方案:
我们可以使用 Vue 的列表渲染来重新创建你的for-loop。我们添加模板引用并获取以下计算的元素引用.main:.box
<template>
<div ref="main" class="main">
<div ref="box" class="box" v-for="i in 10"></div>
</div>
</template>
根据元素参考,我们使用clientWidth和计算安装clientHeight时的盒子尺寸:
<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>
可以将原始 CSS 复制到一个<style>块中:
<style>
.main {
/* insert original .main styles here */
}
.box {
/* insert original .box styles here */
}
</style>
演示 1
您可以对 SVG 路径使用上述相同的步骤来加载随机的 Material Design 图标。例如,将 a 绑定<path>@mdi/js到来自(流行的 MDI 库)的随机 SVG 路径:
创建一个数据属性(名为"icons"),并使用随机范围的图标对其进行初始化@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),
}
},
}
<div ref="box">将前面示例中的替换为<svg ref="box">。在里面<svg>,添加<path :d="icons[i]" />,它绑定到我们上面生成的随机图标。
<template>
<div ref="main" class="main">
<svg ref="box" class="box" v-for="i in 10">
<path :d="icons[i]">/>
</svg>
</div>
</template>
演示 2