ZBLOG

那如果动态activeKey.value === 2时,给width一个变化

您可以通过 动态计算列属性 来实现 activeKey.value === 2 时修改操作列的宽度。以下是完整代码示例:

解决方案

<a-table
  :columns="processedColumns"
  :data-source="data"
  :scroll="{ x: scrollX }"
  :pagination="{
    current: currentPage,
    pageSize: pageSize,
    total: totalRecords,
    pageSizeOptions: ['10', '20', '30', '40', '100'],
    onShowSizeChange: handlePageSizeChange,
    onChange: handlePageChange,
    showQuickJumper: true,
    showSizeChanger: true,
    showTotal: (total, range) => `显示 ${range[0]}~${range[1]}条记录,共 ${total} 条记录`
  }"
>
  <template #bodyCell="{ column, record }">
    <template v-if="column.key === 'operation'">
      <!-- 操作列内容 -->
      <a-button @click="handleAction(record)">操作</a-button>
    </template>
  </template>
</a-table>

<script setup>
import { computed, ref } from 'vue';

const activeKey = ref(2); // 控制条件值

// 原始列定义
const baseColumns = [
  { title: 'ID', dataIndex: 'id', width: 100 },
  { title: '名称', dataIndex: 'name' },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: activeKey.value === 2 ? 300 : 200 // ❌错误写法(不会响应式更新)
  }
];

// ✅正确做法:通过computed动态计算列配置
const processedColumns = computed(() => {
  return baseColumns.map(col => {
    if (col.key === 'operation') {
      return {
        ...col,
        width: activeKey.value === 2 ? 
          300 : // activeKey=2时的宽度 
          200   //默认宽度
      };
    }
    return col;
});
});

// ✅同步更新scroll.x的计算
const scrollX = computed(() => {
 const totalWidth = processedColumns.value.reduce(
   (sum, col) => sum + (col.width || (col.fixed ? col.width ||100 :0)),0);
 return totalWidth >1800? "max-content":undefined;
});
</script>

Key Points:

  1. 动态宽度控制

    • processedColumns会响应activeKey的变化自动重新计算
    • activeKey.value===2时操作列宽度设为300px,否则200px
  2. 注意事项

    • ❌直接写在原始columns里不会响应式更新(Vue无法追踪到变化)
    • ✅必须通过computed返回新对象才能触发响应式更新
  3. 联动效果

    • scroll.x也需用computed同步计算,避免表格滚动区域不更新
  4. TypeScript支持(可选)

interface ColumnProps {
 key?: string;
 width?: number; 
 fixed?: string | boolean;
 [key:string]: any;
}

如果需要更复杂的条件控制(例如同时处理隐藏+宽度变化),可以扩展computed中的逻辑: “`js width:activeKey.value===3? undefined://隐藏时不设宽度

   activeKey.value===2?300:200

”`


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23113

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?