vue中让一个div中的button,从同一行开始依次排列,指定一行放三个,如果放不下了放到下一行,如果点击按钮,按钮会长亮,再次点击恢复,点击之后重新渲染页面,写个案例
时间: 2023-03-20 21:02:33 浏览: 59
以下是一个简单的 Vue.js 示例,其中有一个包含多个按钮的 div,它们被放置在每行三个的网格布局中。当按钮被单击时,它会切换其高亮状态,并在页面上重新渲染以反映该更改。
```html
<template>
<div class="grid-container">
<div
v-for="(button, index) in buttons"
:key="index"
class="grid-item"
:class="{ active: button.active }"
@click="toggleActive(button)"
>
{{ button.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
buttons: [
{ text: "Button 1", active: false },
{ text: "Button 2", active: false },
{ text: "Button 3", active: false },
{ text: "Button 4", active: false },
{ text: "Button 5", active: false },
{ text: "Button 6", active: false },
{ text: "Button 7", active: false },
{ text: "Button 8", active: false },
{ text: "Button 9", active: false },
],
};
},
methods: {
toggleActive(button) {
button.active = !button.active;
this.$forceUpdate();
},
},
};
</script>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(50px, auto);
grid-gap: 10px;
}
.grid-item {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid black;
cursor: pointer;
}
.active {
background-color: yellow;
}
</style>
```
在这个示例中,我们使用了一个包含九个按钮的数组,并使用 `v-for` 指令将它们渲染到页面上。每个按钮被呈现为一个带有文本的 div,并使用一个 `active` 类来控制其高亮状态。我们还设置了一个 `toggleActive` 方法,该方法在按钮上单击时将其高亮状态切换,并使用 `this.$forceUpdate()` 强制重新渲染页面。最后,我们定义了一些 CSS 样式来创建一个网格布局,并定义按钮的外观和行为。