使用Vue 2的完整示例代码,实现點擊物体出現網格根据网格页面移动
时间: 2024-04-08 09:30:28 浏览: 20
下面是一个使用Vue 2的完整示例代码,实现点击物体出现网格,并根据网格进行页面移动:
```html
<template>
<div class="container">
<div class="grid">
<div
v-for="(row, rowIndex) in grid"
:key="rowIndex"
class="row"
>
<div
v-for="(col, colIndex) in row"
:key="colIndex"
:class="{ 'cell': col === 0, 'cell-active': col === 1 }"
@click="moveObject(rowIndex, colIndex)"
></div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
grid: [],
objectPosition: {
row: 0,
col: 0
}
};
},
mounted() {
this.generateGrid();
},
methods: {
generateGrid() {
// 生成网格
const rows = 5;
const cols = 5;
for (let i = 0; i < rows; i++) {
this.grid.push(Array(cols).fill(0));
}
},
moveObject(row, col) {
// 检查目标位置是否在网格范围内
if (row >= 0 && row < this.grid.length && col >= 0 && col < this.grid[0].length) {
// 将当前物体位置设置为普通单元格
this.$set(this.grid[this.objectPosition.row], this.objectPosition.col, 0);
// 更新物体位置
this.objectPosition.row = row;
this.objectPosition.col = col;
// 将新位置设置为活动单元格
this.$set(this.grid[row], col, 1);
}
}
}
};
</script>
<style scoped>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 10px;
}
.row {
display: flex;
}
.cell {
width: 40px;
height: 40px;
background-color: lightgray;
}
.cell-active {
background-color: orange;
}
</style>
```
在这个示例代码中,我们使用 `mounted` 钩子函数在组件加载时生成网格。通过点击单元格,我们可以将物体移动到目标位置,同时在网格中显示物体的位置。
注意,这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。