【问题标题】:Call the javascript function and render element in Svelte在 Svelte 中调用 javascript 函数和渲染元素
【发布时间】:2019-08-13 11:08:32
【问题描述】:

如何在 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} />

DataTableTest.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>

我试了一下

<td on:load=c.formatter(i, d)></td>

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

【问题讨论】:

    标签: svelte svelte-component


    【解决方案1】:

    您可以使用@html template syntax 来实现:

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

    【讨论】:

      【解决方案2】:

      正如@morphyish 提到的,您可以使用@html 模板语法将任意html 插入到DOM 中。

      如果您的表格项的 html 在运行时从 API 动态获取,这很有用 - 例如,当您的网络应用程序无法控制该 html 的生成时。

      如果不是这种情况,并且您的 Web 应用程序可以控制生成 html,那么我建议您创建单独的组件并引用它们,而不是构建一个 html 字符串,使用 &lt;svelte:component&gt; special element 来呈现成分。这样一来,您表格中的所有内容实际上都是一个 svelte 组件,而不是一些任意的 html,并且您可以获得 svelte 提供的所有好处。

      这里有一个类似的例子:https://svelte.dev/repl/e38138607bc445ea95754de83e5e0b8d?version=3.8.0

      【讨论】:

        猜你喜欢
        • 2020-01-17
        • 2020-03-09
        • 2018-12-29
        • 2020-08-10
        • 2021-11-09
        • 1970-01-01
        • 2016-03-14
        • 2020-12-05
        • 1970-01-01
        相关资源
        最近更新 更多