【发布时间】: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 所示.
为什么会这样?最快的修复方法是什么?
【问题讨论】:
-
您需要在
<script context="module">中才能导出可以在其他组件中导入的功能。 -
@johannchopin 你能更准确一点吗?也许发布一个我可以验证的答案。我正在学习 Svelte,我可以使用更多细节。谢谢。
-
是的,很抱歉,我会尽快写信;)