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

Vue3+TailwindCSS标签栏:为AirJordan/NewBalance加空格且不影响组件

Vue3标签导航:显示带空格名称同时保证组件正常加载

你当前的问题是直接修改tabs数组中的文本添加空格后,currentTab的值变成了带空格的字符串,和导入的组件名称(如Airjordans、Newbalance)不匹配,导致组件无法正常加载。解决核心是分离显示文本和组件匹配标识,具体步骤如下:

1. 修改tabs数据结构

把原有的字符串数组改成对象数组,每个对象包含两个属性:

  • displayName:用于页面显示的带空格文本
  • componentKey:和组件文件名一致的标识字符串,用于组件匹配

修改后的data代码:

data() {
  return {
    currentTab: 'Adidas',
    tabs: [
      { displayName: 'Adidas', componentKey: 'Adidas' },
      { displayName: 'Air Jordan', componentKey: 'Airjordans' },
      { displayName: 'Nike', componentKey: 'Nike' },
      { displayName: 'New Balance', componentKey: 'Newbalance' },
      { displayName: 'Reebok', componentKey: 'Reebok' },
      { displayName: 'Converse', componentKey: 'Converse' },
      { displayName: 'Vans', componentKey: 'Vans' },
      { displayName: 'Puma', componentKey: 'Puma' }
    ]
  }
},

2. 调整模板渲染逻辑

在v-for中遍历对象数组,显示时用displayName,而绑定active状态和点击赋值时用componentKey,保证currentTab始终是和组件名一致的字符串:

修改后的模板代码:

<div class="nav">
  <div class="bg-[#f3f4f6]">
    <div class="max-w-7xl flex flex-1 overflow-auto whitespace-nowrap pl-4 pr-4 lg:pl-10 py-3 space-x-4 ">
      <button class="font-rubikreg uppercase text-sm "
        v-for="tab in tabs"
        :key="tab.componentKey"
        :class="['tab-button', { active: currentTab === tab.componentKey } ]"
        @click="currentTab = tab.componentKey"
      >
        {{ tab.displayName }}
      </button>
    </div>
  </div>
</div>

3. 确保组件注册与匹配正常

保持原有的组件导入不变,将导入的组件注册到组件选项中,这样动态组件可以通过currentTab的值(即componentKey)正确匹配:

import Airjordans from "./airjordans.vue";
import Nike from "./nike.vue";
import Adidas from "./adidas.vue";
import Newbalance from "./newbalance.vue";
import Reebok from "./reebok.vue";
import Converse from "./converse.vue";
import Vans from "./vans.vue";
import Puma from "./puma.vue";

export default {
  components: {
    Airjordans,
    Nike,
    Adidas,
    Newbalance,
    Reebok,
    Converse,
    Vans,
    Puma
  },
  // 其他原有代码(data、方法等)
}

4. 动态组件渲染(补充)

如果你是用动态组件渲染对应的内容,只需保持原有的<component>标签即可,因为currentTab现在是和注册组件名完全一致的字符串:

<component :is="currentTab"></component>

这样修改后,页面上会显示带空格的标签名称,同时点击标签时currentTab的值始终和组件名匹配,组件就能正常加载了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:26:11