繁体   English   中英

拖动父组件时,将变量传递给子组件不会响应式更新

[英]Passing variables to child component doesn't update reactively when dragging parent

我有一个组件(“Mover.svelte”)负责为其中的任何组件(在本例中为“Button.svelte”)提供鼠标拖动功能。)

我正在尝试在子 object 中显示当前的 X/Y position,它可以工作,但不会随着 object 的移动而响应更新。 (没有错误消息,只是没有按预期工作。)

我尝试了多种方法来做到这一点,包括 Svelte 的上下文 API,但我尝试过的方法似乎都没有启用反应性。

REPL: https://svelte.dev/repl/1d2b72dbf8aa465fa60b76f2e93fb0cc?version=3.49.0

应用程序.svelte:

<script>
    import Mover from "./Mover.svelte";
    import Button from "./Button.svelte";
</script>

<Mover>
        <Button />
</Mover>

Mover.svelte:

<script>
    
    import { setContext } from 'svelte';

    let moving = false;
    export let x = 120;
    export let y = 130;
    
    setContext('x', x);
    setContext('y', y);

    function dragItem(e) {
        if (moving) {
            x += e.movementX;
            y += e.movementY;
        }
    }
    
</script>

<div on:mousedown={() => moving = true} on:mouseup={() => moving = false} style="left: {x}px; top: {y}px;">
    <slot />
</div>

<svelte:window on:mousemove={dragItem} />

<style>
    div {
        margin: 0;
        padding: 0;
        position: absolute;
        border: 4px solid green;
    }
</style>

Button.svelte:

<script>
    import { getContext } from 'svelte';
    
    let x = getContext('x')
    let y = getContext('y')
    
</script>
    

<button>
    X/Y should update on drag:
    {x}, {y}
</button>
    

<style>
    button {
        border: 4px solid blue;
        margin: 0;
        padding: 12;
    }
</style>

任何帮助将不胜感激。

如果要使用上下文,则必须使用存储,因为设置/获取上下文是一次性操作。 除了通过 props 之外,Reactivity 不会在文件之间传输; 商店可以弥补这一差距。

例如在移动器中:

import { setContext } from 'svelte';
import { writable } from 'svelte/store';

let moving = false;
export let x = 120;
export let y = 130;

const xStore = setContext('x', writable(x));
const yStore = setContext('y', writable(y));

// Synch the stores on change:
$: $xStore = x;
$: $yStore = y;

在 Button 添加$前缀以从商店中读取:

<button>
    X/Y should update on drag:
    {$x}, {$y}
</button>

REPL


作为上下文的替代方案,在这里也可以使用插槽道具

在 mover 中设置插槽上的道具:

<slot {x} {y} />

在 App 中传递它们:

<Mover let:x let:y>
        <Button {x} {y} />
</Mover>

(按钮然后需要为x / y声明道具)

REPL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM