vue2设计一个盒子,点击盒子后周围出现出现网格,再次点击网格,盒子移动到网格处
时间: 2024-04-09 19:29:22 浏览: 17
可以使用Vue.js的指令和数据绑定来实现这个功能。下面是一个实现的示例代码:
```html
<template>
<div>
<div class="box" @click="toggleGrid"></div>
<div v-if="showGrid" class="grid-container">
<div class="grid-item" v-for="(item, index) in gridItems" :key="index" @click="moveBox(index)"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showGrid: false, // 是否显示网格
gridItems: [0, 1, 2, 3, 4, 5, 6, 7, 8], // 网格项
boxPosition: null // 盒子位置
};
},
methods: {
toggleGrid() {
this.showGrid = !this.showGrid;
},
moveBox(index) {
this.boxPosition = index;
this.showGrid = false;
}
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
}
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.grid-item {
width: 100px;
height: 100px;
background-color: red;
}
</style>
```
在上面的代码中,我们通过点击盒子来控制`showGrid`的值,从而显示或隐藏网格。当点击网格项时,会调用`moveBox`方法来更新`boxPosition`的值,并将`showGrid`设置为false,隐藏网格。你可以根据需要自定义样式来美化盒子和网格的外观。
请注意,这只是一个简单的示例,具体实现方法可能会根据你的实际需求有所不同。