请用vue代码实现前端定义九个箱子位置的界面,然后一进入页面后端返回某些箱子坐标,前端就直接展示对应箱子的位置,所在的箱子变色,而且点击箱子可以获取箱子的一些信息
时间: 2023-04-05 18:05:00 浏览: 35
以下是使用Vue实现前端定义九个箱子位置的界面的代码:
```
<template>
<div>
<div v-for="(box, index) in boxes" :key="index" :class="{ 'selected': box.selected }" @click="selectBox(index)">
<p>Box {{ index + 1 }}</p>
<p v-if="box.info">{{ box.info }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
boxes: [
{ x: 0, y: 0, selected: false, info: '' },
{ x: 0, y: 1, selected: false, info: '' },
{ x: 0, y: 2, selected: false, info: '' },
{ x: 1, y: 0, selected: false, info: '' },
{ x: 1, y: 1, selected: false, info: '' },
{ x: 1, y: 2, selected: false, info: '' },
{ x: 2, y: 0, selected: false, info: '' },
{ x: 2, y: 1, selected: false, info: '' },
{ x: 2, y: 2, selected: false, info: '' }
]
}
},
methods: {
selectBox(index) {
this.boxes.forEach((box) => {
box.selected = false
})
this.boxes[index].selected = true
}
}
}
</script>
```
当后端返回某些箱子坐标时,可以在Vue组件的`mounted`生命周期钩子中调用后端API获取数据,并将对应的箱子的`info`属性设置为返回的信息。例如:
```
mounted() {
// 调用后端API获取数据
axios.get('/api/boxes').then((response) => {
const data = response.data
// 将对应的箱子的info属性设置为返回的信息
data.forEach((box) => {
const index = this.boxes.findIndex((b) => b.x === box.x && b.y === box.y)
if (index !== -1) {
this.boxes[index].info = box.info
}
})
})
}
```
当用户点击某个箱子时,可以在`selectBox`方法中获取该箱子的信息,并进行相应的处理。例如:
```
selectBox(index) {
this.boxes.forEach((box) => {
box.selected = false
})
this.boxes[index].selected = true
// 获取箱子的信息
const boxInfo = this.boxes[index].info
// 进行相应的处理
console.log(boxInfo)
}
```