vue2表格鼠标点击表格页面显示表格内容,并且表格被点击的一行变蓝色
时间: 2023-08-21 15:01:53 浏览: 44
你可以使用Vue的事件绑定和样式绑定来实现这个功能。具体步骤如下:
1. 在表格中绑定一个click事件,当用户点击表格时触发该事件。
2. 在事件处理函数中,通过传递的参数获取用户点击的行数。
3. 将该行的数据绑定到一个新的变量中,用于在页面上显示该行的内容。
4. 使用Vue的样式绑定,将被点击的行的背景色设置为蓝色。
下面是一个示例代码:
```html
<template>
<div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index" :class="{ active: index === activeIndex }" @click="handleClick(index)">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.gender }}</td>
</tr>
</tbody>
</table>
<div v-if="activeData">
<p>姓名:{{ activeData.name }}</p>
<p>年龄:{{ activeData.age }}</p>
<p>性别:{{ activeData.gender }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: "张三", age: 18, gender: "男" },
{ name: "李四", age: 20, gender: "女" },
{ name: "王五", age: 22, gender: "男" }
],
activeIndex: -1,
activeData: null
};
},
methods: {
handleClick(index) {
this.activeIndex = index;
this.activeData = this.tableData[index];
}
}
};
</script>
<style scoped>
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 10px;
text-align: left;
border: 1px solid #ccc;
}
.active {
background-color: blue;
color: white;
}
</style>
```
在上面的代码中,我们使用了:class绑定了一个active类,当该行的索引等于activeIndex时,该行就会被设置为蓝色背景。在handleClick方法中,我们将被点击的行的索引存储到activeIndex中,并将该行的数据存储到activeData中,用于在页面上显示该行的内容。