【问题标题】:What causes the "filterUsers is not defined" error in this Svelte App?是什么导致此 Svelte 应用程序中出现“未定义过滤器用户”错误?
【发布时间】:2021-01-12 14:22:06
【问题描述】:

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

应用程序在 Bootstrap 4 表中显示来自 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 所示.

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

【问题讨论】:

  • 您需要在&lt;script context="module"&gt; 中才能导出可以在其他组件中导入的功能。
  • @johannchopin 你能更准确一点吗?也许发布一个我可以验证的答案。我正在学习 Svelte,我可以使用更多细节。谢谢。
  • 是的,很抱歉,我会尽快写信;)

标签: svelte svelte-component


【解决方案1】:

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

我对您的 REPL 进行了一些更改。你可以在这里找到它。

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

【讨论】:

  • 您的解决方案非常专业,但不是很明确。无论如何,谢谢。
猜你喜欢
  • 2021-01-18
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
  • 2015-01-17
  • 1970-01-01
相关资源
最近更新 更多