示例在具有行的表(子组件)中。我需要在每一行中进行文本搜索,并用结果标记行。
我从苗条开始,看起来非常有趣。如何用信号通知所有苗条的子组件(行)以执行行搜索。
我可以切换商店,但是必须有一种根本性的更好方法吗?
Child.svelte:
React
UPDATE这要好得多:
Child.svelte:
<script>
export let child; // child id
import {signal} from './store.js';
let fired = false
$: if ($signal) {
fired = true;
setTimeout(() => fired = false, 500);
}
</script>
{#if fired}
<p>Child-{child}: fired</p>
{/if}
App.svelte:
<script>
import { onDestroy } from 'svelte';
import {search} from './store.js';
export let child;
let result = '';
// observe the search term
const unsubscribe = search.subscribe(value => {
result = `Child-${child} searched : ${value}`;
});
onDestroy(unsubscribe);
</script>
{#if $search}
<p>{result}</p>
{/if
答案 0 :(得分:0)
但是可以在不需要商店的情况下完成。通过搜索作为道具。在嵌套组件中使搜索功能调用成为反应式。现在,斯维尔特将负责搜索更改。
Search.svelte:
<script>
import Row from './Row.svelte';
let data = {
'A': 'Dit is een stuk tekst uit een veel grotere tekst',
'B': 'En hier nog een stuk tekst'
};
let search = '';
function searchHandler(e) {
search = e.target.value;
}
</script>
<style>
table, th {
border-collapse: collapse;
border: 1px solid black;
}
</style>
<h3>Search column <input on:blur={searchHandler}></h3>
<table>
<tr>
<th>Row</th>
<th>Found</th>
<th>Text</th>
</tr>
<Row rowId={'A'} text={data.A} {search}/>
<Row rowId={'B'} text={data.B} {search}/>
</table>
Row.svelte:
<script>
export let rowId;
export let text;
export let search = '';
let result = text;
let found = false;
function searchNow(s) {
let re = new RegExp(s, 'gi');
result = text.replace(re, `<mark>${s}</mark>`);
found = s !== '' && text !== result;
}
$: searchNow(search) // make it reactive
</script>
<style>
td {
border: 1px solid black;
}
</style>
<tr>
<td>{rowId}</td>
<td>{found}</td>
<td>{@html result}</td>
</tr>
您可以使用标记的块语句代替$: searchNow(search)
:
$: { // make it reactive block
console.log('searchNow', search);
searchNow(search)
}