Svelte中Grid.js数据源为对象数组时如何自定义列显示标题
解决方法
你只需要将原columns的字符串数组配置改为对象数组配置,分别指定字段映射标识和显示标题即可,无需修改其他代码:
把原代码里的
const columns = ['Name', 'Salary']
替换为:
const columns = [ // name为表头显示文本,id对应数据对象里的属性名 { name: 'Name', id: 'name' }, { name: 'Earnings', id: 'salary' } ]
原理说明
Grid.js在处理对象数组类型的数据源时,如果columns是字符串格式,会默认把字符串同时作为「匹配数据的属性key」和「表头显示文本」,所以直接修改字符串内容会导致无法匹配到对应属性,列就会被隐藏。拆分id和name两个配置项后,id负责匹配数据属性,name负责控制表头显示,二者互不影响,就能实现改标题又不丢失列的需求。
修改后完整代码
<script> import Grid from "gridjs-svelte" import salaryPlugin from "./TotalSalaryPlugin.js" const columns = [ { name: 'Name', id: 'name' }, { name: 'Earnings', id: 'salary' } ] const data = [ {name: 'John', salary: Math.round(Math.random() * 100000)}, {name: 'Mark', salary: Math.round(Math.random() * 100000)}, {name: 'Josh', salary: Math.round(Math.random() * 100000)}, {name: 'Sara', salary: Math.round(Math.random() * 100000)}, {name: 'Maria', salary: Math.round(Math.random() * 100000)}, ] let grid $: if (grid) { // add plugin grid.plugin.add(salaryPlugin) // we need to force rendering so the plugin can show up grid.forceRender() } </script> <Grid bind:instance={grid} {data} {columns} /> <style global> @import "https://cdn.jsdelivr.net/npm/gridjs/dist/theme/mermaid.min.css"; </style>
内容的提问来源于stack exchange,提问作者crashwap
相关产品推荐
相关产品推荐

