但是我想要这样做:每秒钟,我都会在不同的位置放置一张新图像
JavaScript:
const vue = require("@/assets/images/vue.png");
const bootstrap = require("@/assets/images/bootstrap.png");
const bulma = require("@/assets/images/bulma.png");
export default {
name: "randImg",
data() {
return {
images: [
vue,
bootstrap,
bulma,
css3
],
addedImage: [],
imgTop: -100,
imgLeft: -100,
imgHeight: 64,
imgWidth: 64,
changeInterval: 1000,
selectedImage: ''
}
},
computed: {
imgStyle() {
return {
top: `${this.imgTop}px`,
left: `${this.imgLeft}px`,
height: `${this.imgHeight}px`,
width: `${this.imgWidth}px`
}
}
},
created() {
this.randomImage();
const randomImg = func => setInterval(func, this.changeInterval);
randomImg(this.randomImage);
randomImg(this.addImage);
randomImg(this.randomPosition);
},
methods: {
randomImage() {
const idx = Math.floor(Math.random() * this.images.length);
this.selectedImage = this.images[idx];
},
randomPosition() {
const randomPos = twoSizes => Math.round(Math.random() * twoSizes);
this.imgTop = randomPos(window.innerHeight - this.imgHeight);
this.imgLeft = randomPos(window.innerWidth - this.imgWidth);
},
addImage(){
this.addedImage.push(this.selectedImage);
}
}
}
HTML:
<img :style="imgStyle" class="image" :key="id" :src="image" v-for=" (image,id) in addedImage">
答案 0 :(得分:0)
问题是您的图像绑定到相同的计算imgStyle
,这将所有绑定图像的位置设置为相同的坐标。
要使位置唯一,每个addImage[]
项目应包含自己的位置:
this.addImage.push({
style: {
top: `${this.imgTop}px`,
left: `${this.imgLeft}px`,
height: `${this.imgHeight}px`,
width: `${this.imgWidth}px`
},
src: this.selectedImage
})
这将需要更新模板以绑定到每个迭代器项的子属性:
<img :style="image.style"
:src="image.src"
v-for="image in addedImage">