在 Svelte 中调用 javascript 函数并渲染元素

hat*_*lla 5 svelte svelte-component

如何在 svelte 代码中添加自定义函数调用?例如。在 DataTableTest.svelte 中,我想添加 cellFormatter 函数并使其自动调用并渲染 . 以下是代码:

ABC.svelte

import DataTableTest from "./DataTableTest.svelte";

let columns = [
    {
      label: "ABC",
      property: "abc"
    },
    {
      label: "Items",
      property: "items"
    },
    {
      label: "cellFormatter",
      formatter: function(rowIndex, rowData) {
          return "<div>" + rowData[rowIndex] + "</div>";
      }
    }
  ];


let data = [
  {
    "abc": "dsaaads",
    "items": "dsadsads",
  }

</script>


<DataTableTest title="Test" {data} {columns} />
Run Code Online (Sandbox Code Playgroud)

数据表测试.svelte

<script>
  export let title;
  export let data;
  export let columns = [];
</script>

{title}
<table>
  {#if columns}
    <tr>
      {#each columns as c}
        <td>{c.label}</td>
      {/each}
    </tr>
  {/if}
  {#if data}
    <tbody>
      {#each data as d, i}
        <tr>
          {#each columns as c}
            {#if c.formatter}
              <td on:load=c.formatter(i, d)></td>
            {:else}
              <td>
              {@html d[c.property] ? d[c.property] : ''}
              </td>
            {/if}
          {/each}
        </tr>
      {/each}
    </tbody>
  {/if}
</table>
Run Code Online (Sandbox Code Playgroud)

我尝试过

<td on:load=c.formatter(i, d)></td>
Run Code Online (Sandbox Code Playgroud)

但这不起作用?有人能告诉我在这里该怎么做吗?

Mor*_*ish 7

您可以使用@html 模板语法来实现此目的:

{#if c.formatter}
    <td>
    {@html c.formatter(i, d)}
    </td>
{:else}
    <td>
    {@html d[c.property] ? d[c.property] : ''}
    </td>
{/if}
Run Code Online (Sandbox Code Playgroud)