Closed2

svelte4 で関数経由で取得したプロパティを bind できない問題への対処

hotwatermorninghotwatermorning

https://svelte.dev/repl/47c0ee50589e4e00957dc590e1376080?version=4.2.15

Component.svelte
<script>
	export let array;
	export let onChange = (arr) => {};
</script>

<button on:click={() => {
	array = [...array, array.length + 1]
	onChange(array);
}}>
	Make Changes
</button>

<div>
	<ul>
		{#each array as item}
			<li>{item}</li>
		{/each}
	</ul>
</div>

<style>
	div {
		border: 4px solid blue;
	}
</style>
App.svelte
<script>
	import Component from './Component.svelte';
	let data = {
		arr1: [1, 2, 3],
		arr2: [1, 2, 3]
	};
	const getArray = (type) => {
		if(type == 1) {
			return data.arr1;
		} else {
			return data.arr2;
		}
	}
</script>

<!-- this works -->
<Component bind:array={data.arr1} />
<Component bind:array={data.arr2} />

<!-- this doesn't compile -->
<!--
<Component bind:array={getArray(1)} />
<Component bind:array={getArray(2)} />
-->

<!-- so use this -->
<!--
<Component array={getArray(1)} onChange={(a) => {data.arr1 = a;}} />
<Component array={getArray(2)} onChange={(a) => {data.arr2 = a;}} />
-->

<div>
	<ul>
		{#each data.arr1 as item}
			<li>{item}</li>
		{/each}
	</ul>
		<ul>
		{#each data.arr2 as item}
			<li>{item}</li>
		{/each}
	</ul>
</div>

<button on:click={() => {
	console.log(array);
}}>
	Do something
</button>

<style>
	div {
		border: 4px solid red;
	}
</style>
hotwatermorninghotwatermorning

オブジェクトのプロパティを直接 bind すればオブジェクト自体を reactive に扱えるが、関数経由で取得したプロパティは bind できない。なので更新したことを通知する関数を用意して、それによってオブジェクトを更新する。
参考: https://github.com/sveltejs/svelte/issues/9506

このスクラップは5ヶ月前にクローズされました