我有两个组件在组件树中很远,我对如何在两者之间进行通信有疑问。我有搜索组件、listItems 和一个商店。
store.svelte
<script context="module" lang="ts">
import type {Items} from '../../Models/Items.model';
import { writable } from 'svelte/store';
export const dataItems = writable<Items[]>([]);
const filterInfo = (term:string) => {
dataItems.update(item => {
item.filter(x => {
return x.name.toLowerCase().includes(term.toLowerCase())
|| x.description.toLowerCase().includes(term.toLowerCase());
})
return dataItems;
})
}*/
export const dispatcher = {filterInfo};
</script>
搜索组件
<script lang="ts">
import { dispatcher } from './ViewI/store.svelte';
let value:any;
const handleChange = () => {
dispatcher.filterInfo(value)
console.log(value)
}
</script>
<Search>
<input bind:value
on:input={handleChange}>
</Search>
listItems 组件
import type {Items} from '../../Models/Items.model';
import {dataItems,dispatcher} from './store.svelte';
export let items:Items[] =[];
export let value:any;
$:filterItems = items;
$: {
filterItems = $dataItems.filter((item:any) => {
return item.name || item.description
});
dispatcher.filterInfo(value);
}
</script>
<main>
{#each [...filterItems] as item }
<CardItems
name={item.name}
description={user.description}
id={item.id}
/>
{/each}
</main>
问题是如何将两个组件与您在输入中写入的值进行通信并制作过滤器。