You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过条件仅修改特定导航项激活状态的背景色

实现方案

有两种简洁的方式能实现你要的效果,结合Vue的动态class和CSS就能搞定:

方法一:动态添加专属类名

直接在<b-nav-item>的动态class里增加判断逻辑,给tabid为3的激活项单独加类,再通过CSS设置对应背景色:

修改后的Vue代码

<b-navbar-nav class="mx-auto row nav-slot-custom-bar">
    <template v-for="(item, i) in menus">
        <b-nav-item 
            :href="item.href" 
            class="col" 
            @click="changeTab(item.tabid)" 
            :class="{
                'active': selectNav == item.tabid,
                'active-red': selectNav == item.tabid && item.tabid === 3
            }" 
            :key="i">

            <b-row class="text-center mb-1 nav-btm-icon" :class="{'active': selectNav == item.tabid}">
                <img
                    :src="item.icon" 
                    aria-hidden="true"
                    class="mx-auto"
                    style="width: 31px; height: 31px;"
                    :class="{ 'active': selectNav == item.tabid }"
                />
            </b-row>
        </b-nav-item>
    </template>
</b-navbar-nav>

对应的CSS样式

/* 普通激活项的蓝色背景(可根据需求替换颜色值) */
.nav-slot-custom-bar .b-nav-item.active:not(.active-red) {
    background-color: #42a5f5;
}

/* tabid为3的激活项红色背景(可根据需求替换颜色值) */
.nav-slot-custom-bar .b-nav-item.active-red {
    background-color: #ef5350;
}

方法二:内联动态样式绑定

如果不想额外加类,也可以直接给<b-nav-item>绑定动态style,省去单独写CSS的步骤:

<b-navbar-nav class="mx-auto row nav-slot-custom-bar">
    <template v-for="(item, i) in menus">
        <b-nav-item 
            :href="item.href" 
            class="col" 
            @click="changeTab(item.tabid)" 
            :class="{'active': selectNav == item.tabid}"
            :style="{
                backgroundColor: selectNav == item.tabid && item.tabid === 3 ? '#ef5350' : (selectNav == item.tabid ? '#42a5f5' : 'transparent')
            }"
            :key="i">

            <b-row class="text-center mb-1 nav-btm-icon" :class="{'active': selectNav == item.tabid}">
                <img
                    :src="item.icon" 
                    aria-hidden="true"
                    class="mx-auto"
                    style="width: 31px; height: 31px;"
                    :class="{ 'active': selectNav == item.tabid }"
                />
            </b-row>
        </b-nav-item>
    </template>
</b-navbar-nav>

注意事项

  • 使用方法一时,若Buefy默认样式优先级过高,可在CSS属性后加!important临时覆盖(非必要不推荐)。
  • 所有颜色值都可以替换成你需要的十六进制、RGB值或颜色名称。

内容的提问来源于stack exchange,提问作者felica chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:13:35