vue.jsantd

How to use customRender in a table cell with Antd and VueJS


I'm using antd in my app and I'm trying to do a customRender to show an image in a cell.

My columns array looks like this:

columns: [
        { title: 'Design',
          dataIndex: 'designImage.fileUrl',
          customRender () { // h will be injected
            return '<div id="foo">bar</div>'
          }
        },
]

So, as you might imagine, it turns out like this:

enter image description here

I also tried this way:

{ title: 'Design',
          dataIndex: 'designImage.fileUrl',
          customRender: (text, record, index) => {
            return {
              children: '<img src="https://via.placeholder.com/300.png/09f/fff">'
            }
          }
        },

Unfortunately, that ended up like this:

enter image description here

Can someone please help me figure out what I'm doing wrong?


Solution

  • You can take advantage of the scopedSlots property within columns, and use it to define a scoped slot for the customRender property.

    Here is an example:

    const columns = [
      {
        title: "Image",
        dataIndex: "image",
        key: "image",
        scopedSlots: { customRender: "image-column" },
      },
    ];
    

    Now, in your template, you can use the image-column named slot, like this:

    <a-table :columns="columns" :data-source="tableData">
        <template slot="image-column" slot-scope="image">
            <img :src="image" /> <!-- Add your custom elements here -->
        </template>
    </a-table>
    

    And here is a component example:

    <template>
      <a-table :columns="columns" :data-source="tableData">
        <template slot="image-column" slot-scope="image">
          <img :src="image" />
        </template>
      </a-table>
    </template>
    
    <script>
    const columns = [
      {
        title: "Image",
        dataIndex: "image",
        key: "image",
        scopedSlots: { customRender: "image-column" },
      },
    ];
    
    const tableData = [
      {
        image: "https://picsum.photos/200",
      },
      {
        image: "https://picsum.photos/200",
      },
    ];
    
    export default {
      data() {
        return {
          columns,
          tableData,
        };
      },
    };
    </script>