Vue打地鼠代码
时间: 2023-07-03 22:21:12 浏览: 48
以下是使用Vue实现的打地鼠游戏代码示例:
HTML部分:
```html
<div id="app">
<h1>{{ score }}</h1>
<div class="grid">
<div v-for="(mole, index) in moles" class="cell" :class="{ up: mole.up }" @click="hit(index)">
<div class="mole"></div>
</div>
</div>
</div>
```
CSS部分:
```css
.grid {
display: flex;
flex-wrap: wrap;
width: 400px;
margin: 0 auto;
}
.cell {
width: calc(100% / 3);
height: 100px;
background-color: #d9d9d9;
position: relative;
}
.up .mole {
display: block;
}
.mole {
display: none;
width: 50px;
height: 50px;
background-color: #f0ad4e;
border-radius: 50%;
position: absolute;
top: 25px;
left: 25px;
}
```
JavaScript部分:
```js
new Vue({
el: '#app',
data: {
moles: Array(9).fill({ up: false }),
score: 0,
interval: null
},
methods: {
hit(index) {
if (this.moles[index].up) {
this.score++;
this.moles.splice(index, 1, { up: false });
}
},
start() {
clearInterval(this.interval);
this.interval = setInterval(() => {
const index = Math.floor(Math.random() * 9);
this.moles.splice(index, 1, { up: true });
setTimeout(() => {
this.moles.splice(index, 1, { up: false });
}, 1000);
}, 1500);
}
},
mounted() {
this.start();
}
});
```
这里使用了Vue的数据双向绑定和计时器等功能来实现打地鼠游戏。