svelte - 绑定到对象集合
问题描述
我有一个对象映射,需要将它们的一些字段绑定到标签。当然,我可以将映射转换为数组并使用#each,但在这种情况下,对单个映射条目的更新将更新对所有标签的绑定。我想要原子更新,即将输入绑定到单独的对象,同时使用#each 来构建整个东西(手动映射 50 个左右的项目并不有趣)。有什么办法可以做到这一点?
解决方案
解决方案(有点骇人听闻)如下:
App.svelte:
<script>
import Update from "./Update.js"
let items = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'c' },
{ id: 4, value: 'd' },
{ id: 5, value: 'e' }
];
</script>
<style>
:global(.myclass) {
animation: pulse 2s ease-out
}
@keyframes pulse {
0%, 75% {
background-color: red;
}
100% {
background-color: white;
}
}
</style>
{#each items as item (item.id)}
<input type="text" bind:value={item.value} use:Update={item.value}>
{/each}
Update.js 动作:
export default function update(node, foo) {
let faa = foo
return {
update(foo) {
if (foo === faa) return
faa = foo
// rest of code will only be executed if the value really changed
node.style.animation = 'none';
node.offsetHeight; /* trigger reflow */
node.style.animation = null;
node.classList.add("myclass");
}
}
}
推荐阅读
- javascript - React js - 如何从子组件获取单击事件值到父组件?
- sql-server - 使用前一行的值更新列
- asp.net - 将应用程序从 net framework 2.0 升级到 4.5
- python - 绘制滚动平均值的 x 轴未正确显示
- reactjs - 谷歌浏览器:React 页面无法在谷歌 Chrome 浏览器中打开
- mysql - 带有 DEFAULT CURDATE() 的日期列抛出错误
- ios - 是否可以以编程方式(Swift 4)将谷歌翻译集成到 iOS 应用程序中?
- jenkins-pipeline - Jenkins Multibranch Pipeline 失败,因为它在 Groovy Sandbox 中运行
- python - 如何在显示安装进度的kivy中使用进度条?
- android - 扩展构建变体的 ABI 过滤器不会覆盖其父级