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

AG-GRID调用refreshHeader()切换i18n语言后表头名称不更新

AG-Grid切换i18n语言后表头不更新的问题解决

我在使用AG-Grid(版本ag-grid-community@31.1.1、ag-grid-vue@31.1.1)时遇到问题:切换i18n语言后,表格表头名称无法更新。尝试了两种方式都无效:

  • 手动触发:按钮点击调用updateHeader函数
  • 自动触发:通过watch监听$i18n.locale变化,触发updateHeader函数

已实现的代码

updateHeader函数

updateHeader() {
    console.log('Update header called....');
    if (this.gridApi) {
        console.log('Grid API: ', this.gridApi);
        this.gridApi.refreshHeader();
    }
}

该函数已正常执行,控制台能打印API数据,但表头名称无变化。

watch监听逻辑

watch: {
    '$i18n.locale'(newLocale) {
        console.log('Locale has been changed to: ', newLocale);
        this.updateHeader();
        this.updateGrid++;
    },
    deep: true
},

beforeMount中的列配置

this.columns = [
    {
        editable: false,
        field: 'small_image',
        headerName: this.$t('registers.instructor.photo'),
        menuTabs: [],
        valueFormatter: this.emptyDataFormatter,
        width: 100,
    },
    {
        cellEditor: 'agTextCellEditor',
        cellEditorParams: {
            maxLength: 20,
        },
        editable: true,
        field: 'nickname',
        flex: 1,
        headerName: this.$t('label.nickname'),
        menuTabs: [],
        valueFormatter: this.emptyDataFormatter,
    },
]

问题原因

列配置中的headerName是在beforeMount阶段一次性计算的静态值,切换语言后,headerName仍保留切换前的翻译结果。AG-Grid的refreshHeader()仅刷新表头UI,不会重新计算列定义里的属性值。

解决方案

将列配置改为计算属性,确保语言切换时自动重新生成列配置,同时更新updateHeader函数主动设置新的列定义:

1. 把列定义改为计算属性

computed: {
    columns() {
        return [
            {
                editable: false,
                field: 'small_image',
                headerName: this.$t('registers.instructor.photo'),
                menuTabs: [],
                valueFormatter: this.emptyDataFormatter,
                width: 100,
            },
            {
                cellEditor: 'agTextCellEditor',
                cellEditorParams: {
                    maxLength: 20,
                },
                editable: true,
                field: 'nickname',
                flex: 1,
                headerName: this.$t('label.nickname'),
                menuTabs: [],
                valueFormatter: this.emptyDataFormatter,
            },
        ]
    }
}

2. 修改updateHeader函数

updateHeader() {
    console.log('Update header called....');
    if (this.gridApi) {
        // 重新设置列定义,触发表头更新
        this.gridApi.setColumnDefs(this.columns);
        // 刷新表头UI(可选,setColumnDefs后一般会自动更新)
        this.gridApi.refreshHeader();
    }
}

这样,当i18n语言切换时,计算属性columns会重新生成,updateHeader通过setColumnDefs将新的列定义传给AG-Grid,表头名称就会自动更新为对应语言的翻译值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:05:11