多个按钮,每次只改变一个按钮的样式状态

多个按钮,每次点击的时候只改变一个按钮的状态,有笨办法,但是笨办法写的代码太多了

<a-button :type="type2" class="a1" @click="setMode('PAN')" title="移动(空格键space)" id="2">
    <span class="iconfont icon-hand icon"></span>
</a-button>
<a-button class="a1" @click="setMode('DRAWMASK')" title="笔" id="3">
    <span class="iconfont icon-shiwu-huabi icon"></span>
</a-button>
<a-button :type="type4" class="a1" @click="setMode('RECT')" title="矩形(Q键)" id="4">
    <span class="iconfont icon-huabigongju-juxing icon"></span>
</a-button>
<a-button class="a1" @click="setMode('CIRCLE')" title="圆(W键)" id="5">
    <span class="iconfont icon-yuanxing icon"></span>
</a-button>
<a-button :type="type6" class="a1" @click="setMode('POLYGON')" title="多边形(E键)" id="6">
    <span class="iconfont icon-duobianxing icon"></span>
</a-button>

笨办法是这样的,要改变span标签的样式,写的代码就更多了

if (mode == 'RECT') {
  this.type4 = 'primary'
  this.type2 = ''
  this.type6 = ''
} else if (mode == 'PAN') {
  this.type2 = 'primary'
  this.type4 = ''
  this.type6 = ''
} else if (mode == 'POLYGON') {
  this.type6 = 'primary'
  this.type2 = ''
  this.type4 = ''
}

笨办法写的代码太多了,有没有什么好的办法

阅读 1.8k
3 个回答
// 先建立一个映射表
const modeToType = {
  RECT: 'type4',
  PAN: 'type2',
  POLYGON: 'type6',
}

// 全部复位
Object.keys(modeToType).forEach(type => {
  this[type] = '';
});

// 再针对mode设置
this[modeToType[mode]] = 'primary';

定义一个变量currentType保存当前值,按钮上:type="currentType === 'type2' ? 'primary' : ''"

建议把数据提取出来,如

list: [
  { id: 2, mode: 'PAN', icon: 'hand', title: '移动(空格键space)' },
  ...
]

定义一个变量 curMode: 'PAN',然后 setMode 中加一行代码

curMode: 'PAN',
...
setMode(mode) {
  this.curMode = mode
}

然后循环创建按钮

<a-button v-for="{ id, mode, icon, title } of list"
        :type="mode == curMode ? 'primary' : ''" class="a1" @click="setMode(mode)" :title="title" :id="id">
    <span :class="['iconfont icon', 'icon-' + icon]"></span>
</a-button>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题