如何在 Svelte 中创建自定义事件?
How do I create a custom event in Svelte?
我一直在使用 on:click
并使用 Svelte 寻找活动。如何在子组件中触发可在父组件中捕获的自定义事件?我看过一个教程,我可以在其中传递类似的内容,但是,我无法将其连接起来。
<Component on:customClick={myThing}>
子组件的一些逻辑如下所示:
<script>
export let myThing = '';
<script>
<input type="text" onClick={() => myThing= 'Update'} />
这似乎不起作用,我错过了什么?
您可以从子组件分派事件并在父组件中处理它
// children component
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
let count = 0;
function handleClick() {
count += 1;
dispatch("customClick", {
count
});
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
// parent component
<script>
import ChildrenComponent from "./ChildrenComponent.svelte";
let count;
const handleCustomClick = event => {
count = event.detail.count;
};
</script>
<main>
<p>Parent count: {count || 0}</p>
<ChildrenComponent on:customClick={handleCustomClick}/>
</main>
下面是codesandbox演示
参考:
或者像这样(不派遣):
Parent:
<script>
import Child from "./Child.svelte";
let count = 0;
const handleClick = () => {
count += 1;
};
</script>
<main>
<p>Parent count: {count}</p>
<Child {count} on:click={handleClick} />
</main>
Child:
// child component
<script>
export let count;
</script>
<button on:click>
Clicked {count}
</button>
我一直在使用 on:click
并使用 Svelte 寻找活动。如何在子组件中触发可在父组件中捕获的自定义事件?我看过一个教程,我可以在其中传递类似的内容,但是,我无法将其连接起来。
<Component on:customClick={myThing}>
子组件的一些逻辑如下所示:
<script>
export let myThing = '';
<script>
<input type="text" onClick={() => myThing= 'Update'} />
这似乎不起作用,我错过了什么?
您可以从子组件分派事件并在父组件中处理它
// children component
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
let count = 0;
function handleClick() {
count += 1;
dispatch("customClick", {
count
});
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
// parent component
<script>
import ChildrenComponent from "./ChildrenComponent.svelte";
let count;
const handleCustomClick = event => {
count = event.detail.count;
};
</script>
<main>
<p>Parent count: {count || 0}</p>
<ChildrenComponent on:customClick={handleCustomClick}/>
</main>
下面是codesandbox演示
参考:
或者像这样(不派遣):
Parent:
<script>
import Child from "./Child.svelte";
let count = 0;
const handleClick = () => {
count += 1;
};
</script>
<main>
<p>Parent count: {count}</p>
<Child {count} on:click={handleClick} />
</main>
Child:
// child component
<script>
export let count;
</script>
<button on:click>
Clicked {count}
</button>