Svelte:如何将数据或道具从子组件传递给父组件?
Svelte: How to pass data or props from a child component to the parent?
我会尽量简短。
我有主要成分 app.svelte。我在其中使用了一个名为 Course.svelte 的子组件。我正在使用 {#each} 块多次重复相同的组件。问题是我希望 app.svelte 知道每当单个组件是 on:clicked。
现在我正在处理 Course.svelte 组件中的 on:click 事件。像这样,App.svelte 永远不会知道这件事。
我该怎么办?
Course.svelte 的片段以及我如何处理 on:click 事件:
<script>
function handleClick() {
if (state == courseStates.CLOSED) {
//Handle closed course
} else {
if (state === courseStates.READY) {
passCourse();
} else if (state === courseStates.PASS) {
failCourse();
}
}
}
function passCourse() {
state = courseStates.PASS;
}
function failCourse() {
state = courseStates.READY;
}
</script>
<div on:click={handleClick} class="text-center course btn {buttonClass}">
<h1>{name}</h1>
<h4>{code} - {credit} Credit Hours - Term {term}</h4>
</div>
App.svelte 的一个片段,我想在其中通过单击课程来维护每门课程的状态,因为它会随着时间的推移而变化:
<div class="row">
{#each courses as course}
{#if course.term == term}
<Course
state={course.state}
name={course.name}
credit={course.credit}
term={course.term}
code={course.code}
on:removecourse={removeCourse} />
{/if}
{/each}
</div>
您可以通过添加 App.svelte bind:state={course.state}
使用 two-way 数据绑定。现在,如果 Course.svelte 中的值发生变化,App.svelte 中的值将被更新。
这是一个 REPL:
https://svelte.dev/repl/48649794a7144d63bbde67a2db2f67a9?version=3.24.1
有更好的方法来处理这个问题,您在使用 two-way 绑定时应该小心。使用 two-way 绑定,您将很容易弄乱数据流。
处理数据流的更好方法:
- 将函数从父级传递给子级
- 将整个 data-object 传递给子组件
- 使用
store
- 使用自定义事件
createEventDispatcher
我会尽量简短。 我有主要成分 app.svelte。我在其中使用了一个名为 Course.svelte 的子组件。我正在使用 {#each} 块多次重复相同的组件。问题是我希望 app.svelte 知道每当单个组件是 on:clicked。 现在我正在处理 Course.svelte 组件中的 on:click 事件。像这样,App.svelte 永远不会知道这件事。 我该怎么办?
Course.svelte 的片段以及我如何处理 on:click 事件:
<script>
function handleClick() {
if (state == courseStates.CLOSED) {
//Handle closed course
} else {
if (state === courseStates.READY) {
passCourse();
} else if (state === courseStates.PASS) {
failCourse();
}
}
}
function passCourse() {
state = courseStates.PASS;
}
function failCourse() {
state = courseStates.READY;
}
</script>
<div on:click={handleClick} class="text-center course btn {buttonClass}">
<h1>{name}</h1>
<h4>{code} - {credit} Credit Hours - Term {term}</h4>
</div>
App.svelte 的一个片段,我想在其中通过单击课程来维护每门课程的状态,因为它会随着时间的推移而变化:
<div class="row">
{#each courses as course}
{#if course.term == term}
<Course
state={course.state}
name={course.name}
credit={course.credit}
term={course.term}
code={course.code}
on:removecourse={removeCourse} />
{/if}
{/each}
</div>
您可以通过添加 App.svelte bind:state={course.state}
使用 two-way 数据绑定。现在,如果 Course.svelte 中的值发生变化,App.svelte 中的值将被更新。
这是一个 REPL:
https://svelte.dev/repl/48649794a7144d63bbde67a2db2f67a9?version=3.24.1
有更好的方法来处理这个问题,您在使用 two-way 绑定时应该小心。使用 two-way 绑定,您将很容易弄乱数据流。
处理数据流的更好方法:
- 将函数从父级传递给子级
- 将整个 data-object 传递给子组件
- 使用
store
- 使用自定义事件
createEventDispatcher