【问题标题】:Svelte watch an object propertySvelte 观察对象属性
【发布时间】:2022-01-03 10:24:40
【问题描述】:

我有一个事件列表

let searchedEvents=[] // events array which will be filled with search results later

当这个数组被填充时(比如n 结果),用户界面将显示n 用户可以编辑的表单。编辑的第一个表单 (searchedEvents[0]) 应该更新所有其他表单(例如,假设表单 1 中有一个字段 num。如果第一个表单的 num 字段被更新,所有其他表单应该显示该字段的相同值)。

为了实现这一点,我有一个eventZero = searchedEvents[0](并且只要searchedEvents 数组更新,就会运行此语句。

那我就这样看eventZero.num

$: myWatch(eventZero.num)

但每当用户编辑表单中的 num 字段时,这不会触发 myWatch

即使像$: myWatch(eventZero) 这样直接看也行不通。 那么如何在 svelte 中实现这一点呢?

【问题讨论】:

  • 你能不能做一个小的REPL的逻辑?

标签: svelte


【解决方案1】:

我的想法是监视整个数组,但设置监视程序,使其仅在满足条件的值更改时才做出反应(在这种情况下是第一个值)。所以,这是我的方法:

// App.svelte
<script>
    import { onMount } from 'svelte';
    import InputField from './InputField.svelte';

    let searchedEvents = [];

    // setting up the initial array
    let n = 10;
    onMount(() => {
        searchedEvents = [...Array(n)].map((_, i) => ({ num: i, idx: i }));
    });

    // function to set array values programatically
    const setToFirst = (arr) => arr.map(({ num, ...rest }, i, d) => ({ num: d[0].num, ...rest }))
    
    // setting up watcher with "oldValue"
    let watchedNum = 0 ?? searchedEvents[0].num
    $: if (searchedEvents.length && searchedEvents[0].num !== watchedNum) {
        searchedEvents = setToFirst(searchedEvents)
        watchedNum = searchedEvents[0].num
    }
    
</script>

{#each searchedEvents as event}
    {event.idx}: <InputField bind:val={event.num} /><br />
{/each}
// InputField.svelte
<script>
    export let val;
</script>

<input bind:value={val} />

您可以找到有效的 sn-p here

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多