我试图了解如何与 Svelte 组件进行通信。在我的应用程序中,我创建了两个组件。在其中一个Antescript.svelte中,我使用bind与 App.svelte 进行通信;在另一个Postscript.svelte中,我使用调度进行通信。
一种方法优于另一种方法吗?
我使用一个方法而不是另一个方法可能会遇到问题吗?
调度方法肯定需要更多编码,这是一个问题吗?
应用程序.svelte
<h1>{antescript} {junction} {postscript}</h1>
<div>
<AnteScript bind:antescript={antescript}/>
</div>
<div>
<PostScript on:message={postscriptChanged} {postscript}/>
</div>
<script>
import AnteScript from "./AnteScript.svelte";
import PostScript from "./PostScript.svelte";
let antescript = 'start';
let junction = 'and';
let postscript = 'finish';
function postscriptChanged(event) {
postscript = event.detail.text;
}
</script>
Run Code Online (Sandbox Code Playgroud)
AnteScript.svelte
<input type="text" bind:value={antescript} />
<script>
export let antescript;
</script>
Run Code Online (Sandbox Code Playgroud)
PostScript.svelte
<input id="postscript" type="text" on:input={textChanged} value={postscript}/>
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let postscript;
function textChanged() {
let postscript_input = document.getElementById("postscript");
dispatch('message', {
text: postscript_input.value
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
Svelte 提出了多种组件之间通信的方式。它主要取决于组件之间的关系以及组件应如何应对变化:
以下文章将为您提供更多详细信息: https://betterprogramming.pub/6-ways-to-do-component-communications-in-svelte-b3f2a483913c
你的处理方式看起来完全没问题,这是 API 的问题。但您也可以绑定该postscript值,不是吗?
| 归档时间: |
|
| 查看次数: |
493 次 |
| 最近记录: |