svelte - 在 svelte 中的 2 个子组件之间传递数据的正确方法是什么
问题描述
我在 2 个子组件之间传递数据的正确方法是什么?我所拥有的是一个非常简单的结构:
APP.svelte
<script>
import Carmaterial from "./Carmaterial.svelte";
import Carcolor from "./Carcolor.svelte";
const carMaterial = {
title: 'Please select car material',
property: 'carMaterial',
options: [
{id: 0, name: 'Gold'},
{id: 1, name: 'Titanium'},
{id: 2, name: 'Silver'}
],
};
const carColor = {
title: 'Please select car color',
property: 'carColor',
options: [
{id: 0, name: 'Black'},
{id: 1, name: 'Blue'},
{id: 2, name: 'Orange'},
{id: 3, name: 'White'},
{id: 4, name: 'Yellow'},
{id: 5, name: 'Green'},
],
};
</script>
//here im passing all of the data to the components itself
<Carmaterial {...carMaterial} />
<Carcolor {...carColor}/>
<style>
</style>
这些组件基本上是 2 组无线电输入:
Carmaterial.svelte
<script>
export let property;
export let title;
export let options;
//im using this in order to predefine value
export let selected = options[1];
</script>
<h3>{title}</h3>
<ul>
{#each options as option (option.id)}
<li>
<label>
<input
value={option.id}
bind:group={selected.id}
type="radio"
name={property}>
{option.name}
</label>
</li>
{/each}
</ul>
<style lang="scss">
</style>
Carcolor.svelte
<script>
export let property;
export let title;
export let options;
//im using this in order to predefine value
export let selected = options[2];
</script>
<h3>{title}</h3>
<ul>
{#each options as option (option.id)}
<li>
<label>
<input
value={option.id}
bind:group={selected.id}
type="radio"
name={property}>
{option.name}
</label>
</li>
{/each}
</ul>
<style lang="scss"></style>
最后我的输出看起来像
h3 with Title
ul li with material options
h3 with Title
ul li with color options
What im trying to achieve is -> I need somehow to disable "Orange" and "White" radio buttons (from carColor group) when "Titanium" material (from carMaterial group) is selected.
不使用 Shop 可以吗?如果是的话,如果我不想弄乱我的数据流,最好的解决方案是什么..
解决方案
基本上有两种方式:
使用商店,这将为组件提供一个“共享”的地方来获取他们的数据
将数据移动到父组件并将其传递给子组件:
<script>
let selectedMaterial = 'paper';
let selectedColor = 'orange';
</script>
<Carmaterial {...carMaterial} {selectedColor} bind:selectedMaterial />
<Carcolor {...carColor} {selectedMaterial} bind:selectedColor />
请注意,selected
我将在相应的组件中使用selectedMaterial
and而不是使用,selectedColor
只是为了使其更短。
基本原理很容易理解:将 1 个组件的选择绑定到父组件,将此选择传递给另一个组件。
您已经将可能的数据保存在父级中,这似乎是一件很自然的事情。
推荐阅读
- html - 如何在主div的底部制作div?
- akka - 演员与普通物体
- jquery - 特定 div 中的淡出 jquery
- python-3.x - 在 Python 中打印原始文本
- excel - 使用数组跳过特定工作表
- php - 通过 remember_me 登录后将用户重定向到不同的路由,具体取决于他们在 Symfony 4 中的角色
- google-cloud-platform - 在 GCP 中使用 Cloud Pub/Sub 主题安排 bq 命令行
- laravel - 在 laravel vuejs Axios 中上传 pdf 文件
- c# - 如何使用静态方法初始化 ServiceBusConnectionStringBuilder 对象并重置它 c#
- ionic-framework - Ionic 4、Azure Active Directory B2C 与 Google 作为身份提供者