Скажем, у меня есть это основное приложение:
import Field from '../components/Field.svelte';
var fields = [
{
id: 'Check',
type: 'CheckBox',
value: false,
},
{
id: 'Text'
}
];
var components = {};
$: console.log(components);
</script>
<style>
</style>
<form>
{#each fields as item}
<Field {...item} bind:bind={components[item.bind]} bind:this={components[item.id]}></Field>
{/each}
</form>
и у меня есть два компонента, CheckBox
и TextArea
, оба просто реализуют ввод HTML, а компонент поля реализован следующим образом:
import CheckBox from './CheckBox.svelte';
import TextArea from './TextArea.svelte';
export let attributes = {};
export let type = 'TextArea';
export let value = '';
export let id;
export let bind;
const fieldComponents = {
'CheckBox': CheckBox,
'TextArea': TextArea
};
</script>
<svelte:component {bind} {id} value={value} this={fieldComponents[type]} {attributes}></svelte:component>
Таким образом я создаю динамическую форму с флажком и текстовым полем.
Я хочу, чтобы атрибут "bind" был доступен изнутри компонента и чтобы иметь возможность связывать другой компонент. Таким образом я смогу достичь чего-то вроде этого:
<input type="checkbox" bind:checked={bind.value}>
это означает, что если текстовое поле будет иметь текст, флажок будет установлен, если он пуст, флажок будет снят.
после рендеринга всех компонентов я могу получить к ним доступ, используя объект components
, потому что я привязываю их так bind:this={components[item.id]}
но до их рендеринга я не могу получить к ним доступ, есть ли способ сделать так, чтобы один компонент мог динамически связываться с другим? Я продемонстрировал использование только двух компонентов, с таким же успехом это может быть большой набор компонентов.
Я хочу определить привязку с помощью свойства bind
внутри массива fields
, которое соответствует id
другого поля.