vue 点击按钮,边框变色
要求:第一个按钮是选中的状态,点击按钮变背景色
效果图:
点击前:
点击后:
先写一个简单的按钮样式
<template> <div> <button class="btn1">按钮1</button> <button class="btn2">按钮2</button> </div> </template> <script> export default { data() { return {}; }, methods: {} }; </script> <style scoped> .btn1 { width: 72px; height: 20px; border: 1px solid #d9d9d9; border: 0; outline: none; } .btn2 { width: 72px; height: 20px; border: 1px solid #d9d9d9; border: 0; outline: none; } </style>
然后在需要写点击之后的样式和逻辑代码:
加一个三元表达式和样式,以及点击事件
<button class="btn1" @click="btn1data()" :class="showmode ? 'active' : 'btn1'" > 按钮1 </button> <button class="btn2" @click="btn2data()" :class="!showmode ? 'active' : 'btn1'" > 按钮2 </button> return { showmode: true }; methods: { btn1data() { this.showmode = true; }, btn2data() { this.showmode = false; } .btn2.active { background: red; } }
完整代码:
html:
<template> <div> <button class="btn1" @click="btn1data()" :class="showmode ? 'active' : 'btn1'" > 按钮1 </button> <button class="btn2" @click="btn2data()" :class="!showmode ? 'active' : 'btn1'" > 按钮2 </button> </div> </template>
css:
.btn1.active,
.btn2.active {
background: red;
}
js:
<script> export default { data() { return { showmode: true }; }, methods: { btn1data() { this.showmode = true; }, btn2data() { this.showmode = false; } } }; </script>
然后就大功告成啦!