Vue JS - 如何使用按钮创建颜色切换器
Vue JS - How to create a color switcher using buttons
我有两个按钮,当按下第一个按钮时,它的背景发生变化(例如,红色),第二个按钮的背景颜色变为白色,反之亦然,当按下第二个按钮时,第二个按钮的背景颜色变成红色,第一个按钮的颜色变成白色
<template>
<div class="btn-group">
<div>
<button>First Click</button>
</div>
<div>
<button>Second Click</button>
</div>
</div>
</template>
<script>
export default {
isCheck: false,
};
</script>
<style scoped>
.btn-group div button {
background: white;
color: red;
padding: 10px;
}
</style>
您还可以看到给定的code in codesandbox
我编辑了我的问题,忘了再强调两个细微差别,按钮的初始背景颜色是白色,此外,当您单击特定按钮时,按钮文本颜色应该改变,原始按钮颜色是红色单击它时,文本颜色应变为白色
您可以使用状态变量并相应地将 css 类 应用到您的按钮,例如:
<template>
<div class="btn-group">
<div>
<button
:class="{ red: state === 1, white: state === 2 }"
@click="setState(1)"
>First Click</button>
</div>
<div>
<button
:class="{ red: state === 2, white: state === 1 }"
@click="setState(2)"
>Second Click</button>
</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
isCheck: false,
props: {
msg: String,
},
data() {
return {
state: 0
}
},
methods: {
setState(s) {
this.state = s;
}
}
};
</script>
<style scoped>
.btn-group {
display: flex;
justify-content: center;
}
button {
background: white;
color: red;
padding: 10px;
}
.red {
background: red;
color: white;
}
.white {
background: white;
color: red;
}
</style>
我有两个按钮,当按下第一个按钮时,它的背景发生变化(例如,红色),第二个按钮的背景颜色变为白色,反之亦然,当按下第二个按钮时,第二个按钮的背景颜色变成红色,第一个按钮的颜色变成白色
<template>
<div class="btn-group">
<div>
<button>First Click</button>
</div>
<div>
<button>Second Click</button>
</div>
</div>
</template>
<script>
export default {
isCheck: false,
};
</script>
<style scoped>
.btn-group div button {
background: white;
color: red;
padding: 10px;
}
</style>
您还可以看到给定的code in codesandbox
我编辑了我的问题,忘了再强调两个细微差别,按钮的初始背景颜色是白色,此外,当您单击特定按钮时,按钮文本颜色应该改变,原始按钮颜色是红色单击它时,文本颜色应变为白色
您可以使用状态变量并相应地将 css 类 应用到您的按钮,例如:
<template>
<div class="btn-group">
<div>
<button
:class="{ red: state === 1, white: state === 2 }"
@click="setState(1)"
>First Click</button>
</div>
<div>
<button
:class="{ red: state === 2, white: state === 1 }"
@click="setState(2)"
>Second Click</button>
</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
isCheck: false,
props: {
msg: String,
},
data() {
return {
state: 0
}
},
methods: {
setState(s) {
this.state = s;
}
}
};
</script>
<style scoped>
.btn-group {
display: flex;
justify-content: center;
}
button {
background: white;
color: red;
padding: 10px;
}
.red {
background: red;
color: white;
}
.white {
background: white;
color: red;
}
</style>