英文:
In Svelte, is #key the proper way to make a block reactive if it makes no local reference to variables?
问题
在下面的代码中,我调用一个函数(getFormattedValue
)来获取要显示的值。这个函数是对另一个函数(node.getFormattedAttrValue
)的包装,它提供了一个共同的参数 data
,这样我就不必为每个要显示的属性重复使用数据参数了。每个属性只需提供其名称。但在这样做之后,组件的主体不再响应(例如,在数据变化时)。显然,在{}
标记中没有data
使它们不具有响应性。但我不想一直重复相同的参数。那么该怎么办?
<script>
export let data, node
const getFormattedValue = (synonym) => node.getFormattedAttrValue(data, synonym)
</script>
<Card>
<span slot="Body">
<li>{getFormattedValue("CURRENT_VALUE")}</li>
<li>{getFormattedValue("MIN_VALUE")}</li>
<li>{getFormattedValue("MAX_VALUE")}</li>
<li>{getFormattedValue("PCT_CONSUMED")}%</li>
</span>
</Card>
我唯一能够让它重新响应而不将data
重新放入参数列表的方法是添加一个key块:
{#key data}
<li>{getFormattedValue("CURRENT_VALUE")}</li>
<li>{getFormattedValue("MIN_VALUE")}</li>
<li>{getFormattedValue("MAX_VALUE")}</li>
<li>{getFormattedValue("PCT_CONSUMED")}%</li>
{/key}
但我了解到key
会完全销毁一切并重新构建,因此它似乎过于重-handed。有没有更好的方法来做到这一点?
英文:
In the code below, I am calling a function (getFormattedValue
) to obtain the value to display. That is a wrapper around another function (node.getFormattedAttrValue
) that supplies a common parameter, data
so I don't have to keep repeating the data parameter for each attribute I'm displaying... the only thing each must provide is its name. But after doing this, the component body stopped reacting (e.g. on change to data). Apparently not having data
in the { }
tags made them non-reactive. But I don't want to keep repeating that same parameter. So what to do?
<script>
export let data, node
const getFormattedValue = (synonym) => node.getFormattedAttrValue(data,synonym)
</script>
<Card>
<span slot="Body">
<li>{getFormattedValue("CURRENT_VALUE")}</li>
<li>{getFormattedValue("MIN_VALUE")}</li>
<li>{getFormattedValue("MAX_VALUE")}</li>
<li>{getFormattedValue("PCT_CONSUMED")}%</li>
</span>
</Card>
The only way I could get it to react again without putting data
back into the parameter list is to add a key block on it:
{#key data}
<li>{getFormattedValue("CURRENT_VALUE")}</li>
<li>{getFormattedValue("MIN_VALUE")}</li>
<li>{getFormattedValue("MAX_VALUE")}</li>
<li>{getFormattedValue("PCT_CONSUMED")}%</li>
{/key}
But I read that key
completely destroys everything and rebuilds it, so it sounds rather heavy-handed. Is there a better way to do this?
答案1
得分: 3
你可以以响应式的方式定义函数:
$: getFormattedValue = (synonym) => node.getFormattedAttrValue(data, synonym)
英文:
You can define functions reactively as well:
$: getFormattedValue = (synonym) => node.getFormattedAttrValue(data,synonym)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论