gpt4 book ai didi

javascript - 将变量传递给自定义 Svelte Web 组件

转载 作者:行者123 更新时间:2023-12-05 09:08:45 27 4
gpt4 key购买 nike

我使用 Svelte 创建了简单的自定义 Web 组件。它已经被编译并且看起来应该可以正常工作,但是有困难。我试图将一些变量传递给 prop,但一直未定义,但如果我传递一些字符串

Result.svelte 组件

<svelte:options tag="svelte-result" />

<script>
export let result = {metadata: {}, transfers: []};
export let string = 'no string';
</script>

<div class="result__wrapper">
{string}
<div class="result__metadata">
<div>{result.metadata.offset}</div>
<div>{result.metadata.limit}</div>
<div>{result.metadata.total}</div>
</div>
</div>

当它被编译时,我正在使用它

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Svelte test</title>
<script defer src="/svelte/wapi-client/svelte-component.js"></script>

</head>
<body>
<div id="test"></div>
</body>

<script>
const data = {
metadata: {
limit: 20,
offset: 0,
total: 311301
},
transfers: [
{
amount: "7.95",
identifier: "9cd9901f-44a5-4436-9aef-880354bbe2e4"
}
]
};

document.getElementById('test').innerHTML = `
<svelte-result string="works" result=${data}></svelte-result>`;
</script>
</html>

data 变量未传递给组件,但字符串传递并正确显示...我做错了什么?如何将 data 变量传递给组件?

最佳答案

您不能将对象作为属性传递给自定义元素。您需要在传递对象之前对其进行字符串化。

index.html

...
document.getElementById('test').innerHTML = `
<svelte-result string="works" result=${JSON.stringify(data)}></svelte-result>`;
...

Foo.svelte

<svelte:options tag="svelte-result" />

<script>
export let result = {metadata: {}, transfers: []};
export let string = 'no string';

$: _result = typeof result === 'string' ? JSON.parse(result) : result;
</script>

<div class="result__wrapper">
{string}
<div class="result__metadata">
<div>{_result.metadata.offset}</div>
<div>{_result.metadata.limit}</div>
<div>{_result.metadata.total}</div>
</div>
</div>

关于javascript - 将变量传递给自定义 Svelte Web 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63072084/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com