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

Vue.js+Vuetify v-data-table表头换行无效问题求助

实现Vuetify v-data-table表头换行的方法

在Vuetify 2.x版本中,直接在表头的text属性里加\n不会生效,因为组件默认会把文本当成纯文本渲染,不会解析换行符。可以用以下两种方法解决:

方法一:使用HTML换行标签并开启HTML渲染

给表头对象添加html: true属性,同时将text里的\n替换为<br>标签,让组件解析HTML内容:

修改后的headers数据:

headers: [
  { text: 'Calories<br>(per 100g)', align: 'center', sortable: false, value: 'calories', html: true },
  { text: 'Protein<br>(per 100g)', align: 'center', sortable: false, value: 'protein', html: true },
  { text: 'Carbohydrates<br>(per 100g)', align: 'center', sortable: false, value: 'carbohydrates', html: true },
],

这样组件会解析<br>标签,实现表头换行。

方法二:使用自定义表头插槽

通过v-slot:header.{value}插槽完全自定义表头内容,这种方式更灵活,能实现更复杂的排版:

修改后的模板代码:

<v-data-table
  :headers="headers"
  :items="items"
  :items-per-page="itemsPerPage"
  hide-default-footer
  class="elevation-1">
  <!-- 自定义Calories表头 -->
  <template v-slot:header.calories>
    <div class="text-center">
      Calories<br>(per 100g)
    </div>
  </template>
  <!-- 自定义Protein表头 -->
  <template v-slot:header.protein>
    <div class="text-center">
      Protein<br>(per 100g)
    </div>
  </template>
  <!-- 自定义Carbohydrates表头 -->
  <template v-slot:header.carbohydrates>
    <div class="text-center">
      Carbohydrates<br>(per 100g)
    </div>
  </template>
</v-data-table>

这种方法不需要修改headers里的text属性,直接通过插槽自定义表头的HTML结构,同样能实现换行效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:08:18