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

map函数内引用totalItems数组undefined 实现b-table点击切换列显隐问题

问题原因

  • 你在map方法中使用了普通匿名函数作为回调,普通函数的this会指向自身执行上下文,而非Vue组件实例,因此回调内部无法访问到挂载在Vue实例上的totalItems数组,外部能正常打印是因为外部的this仍然指向组件实例。
  • 额外逻辑优化点:你只是需要遍历数组修改元素,不需要生成新数组,用forEach比map更符合语义;原有逻辑中列状态切换的splice操作重复,会导致列配置更新不符合预期。

修复方案

将map的普通回调改为箭头函数,箭头函数不会绑定自身this,会继承外层作用域的this(也就是Vue组件实例),同时调整逻辑优化状态切换,修改后的clickColumn方法如下:

clickColumn(data) {
  const column = this.showingFields.find(element => element.key == data.field.key);
  const fieldKey = column.key;

  // 列已隐藏,点击后恢复显示
  if (column.collapsed) {
    this.showingItems.forEach((elem, index) => {
      elem[fieldKey] = this.totalItems[index][fieldKey];
    });
    // 替换为展开状态的字段配置
    this.showingFields.splice(column.index, 1, {...this.totalFields[column.index], collapsed: false});
  } 
  // 列已显示,点击后隐藏
  else {
    this.showingItems.forEach(elem => {
      delete elem[fieldKey];
    });
    // 替换为折叠状态的字段配置
    this.showingFields.splice(column.index, 1, {...this.collapsedFields[column.index], collapsed: true});
  }
}

可选优化

如果需要避免修改showingItems时联动修改totalItems的引用类型数据(比如示例中的name对象),可以在赋值时做深拷贝:

elem[fieldKey] = JSON.parse(JSON.stringify(this.totalItems[index][fieldKey]));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:36:03