是什么导致此 Svelte 应用程序出现 "filterUsers is not defined" 错误?

What causes the "filterUsers is not defined" error in this Svelte App?

我正在开发一个小型 Svelte 应用程序,用于学习目的(我是 Svelte 的新手)。

应用程序在 Bootstrap 4 table.

中显示来自 randomuser.me API 的 JSON 用户

我目前正在将应用程序分解成组件。

App.svelte我有:

<script>
    const apiURL = "https://randomuser.me/api/";
    import { onMount } from "svelte";
    import { fade, fly } from 'svelte/transition';
    import { flip } from 'svelte/animate';
    import Search from './Search.svelte';
    let users = [];
    $:filteredUsers = users;
    
     onMount(() => {
        getUsers();
        filterUsers();
    });
    
    const getUsers = () => {
        let getFrom = "&results=20&inc=name,location,email,cell,picture";
        fetch(`${apiURL}?${getFrom}`)
            .then(res => res.json())
            .then((data) => users = data.results);
    };
    
    const deleteUser = (user) => {
        let itemIdx = filteredUsers.findIndex(x => x == user);
        filteredUsers.splice(itemIdx,1);
        filteredUsers = filteredUsers;
    }
</script>

搜索功能已移动到它自己的组件中:

<script>
    export let stringToMatch = '';
    export let filteredUsers = [];
    
        export const filterUsers = () => {
        filteredUsers = users;
    
        if(stringToMatch){
            filteredUsers = users.filter(user => {
                return user.name.first.toLowerCase().includes(stringToMatch.toLowerCase())
                    || user.name.last.toLowerCase().includes(stringToMatch.toLowerCase())
                    || user.location.city.toLowerCase().includes(stringToMatch.toLowerCase());
            });
        }
    }
</script>

<div class="search p-2">
   <input class="form-control" type="text" placeholder="Search..." bind:value="{stringToMatch}" on:input="{filterUsers}">
</div>

即使我已经从 Search.svelte 中导出变量并将搜索组件导入到 App.svelte 组件中,我仍然收到 filterUsers is not defined 错误,如 REPL.

为什么会这样?什么是最快的修复?

搜索组件应该负责发出搜索词,或者您可以编写一个过滤函数并将其传递给搜索,但您正在调用父函数中的子函数。据我所知 export 是延迟延迟。这意味着 Child 组件期望 prop 实际上没有导出变量。您可以在此处阅读有关组件通信的更多信息:https://svelte.dev/docs#1_export_creates_a_component_prop.

我对你的 REPL 做了一些修改。你可以在这里找到它。

https://svelte.dev/repl/9da70df5e25646aabc5c37355b82c4a3?version=3.28.0