svelte - 为什么我不能在此 Svelte 应用程序的组件中保留与组件相关的操作?
问题描述
我正在 Svelte 中开发一个用于学习目的的小型用户应用程序(我是 Svelte 的新手)。
在 App.Svelte 中,我遍历一组用户:
<script>
const apiURL = "https://randomuser.me/api/";
import { onMount } from "svelte";
import Search from './Search.svelte';
import User from './User.svelte';
let users = [];
let stringToMatch = "";
$:filteredUsers = users;
onMount(() => {
getUsers();
});
const getUsers = () => {
let getFrom = "&results=20&inc=name,location,email,cell,picture";
fetch(`${apiURL}?${getFrom}`)
.then(res => res.json())
.then((data) => users = data.results);
};
let filterUsers = () => {
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());
});
} else filteredUsers = users;
};
</script>
<div class="container-fluid">
<div class="card bg-light mb-2 overflow-hidden">
<div class="card-header px-2 py-0 d-flex">
<h6 class="text-dark m-0 align-self-center">Members Area</h6>
</div>
<div class="card-body bg-white p-0">
<Search {filterUsers} bind:stringToMatch={stringToMatch} />
{#if filteredUsers.length > 0}
<table class="table users-table m-0">
<thead>
<tr>
<th class="text-right">#</th>
<th>Name</th>
<th>Lives in</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
{#each filteredUsers as user,index (user)}
<User {user} {index} on:Delete = {deleteUser(user)} />
{/each}
</tbody>
</table>
{:else}
<p class="text-center text-muted my-3">No members found</p>
{/if}
</div>
</div>
</div>
从上面的循环中可以看出,我显示了来自User.svelte
组件的每个用户。每个与用户相关的操作(例如删除用户)都显示在该组件中,这似乎是合乎逻辑的。所以,我在这里:
const dispatch = createEventDispatcher();
const Delete = () => dispatch("deleteUser", user);
const deleteUser = (user) => {
let itemIdx = filteredUsers.findIndex(x => x == user);
filteredUsers.splice(itemIdx, 1);
filteredUsers = filteredUsers;
}
然而,我得到了这个'deleteUser' is not defined
错误,正如可以在REPL中看到的那样。
问题)
- 我究竟做错了什么?
- 我怎样才能保留该
deleteUser
方法User.svelte
并成功使用它?
解决方案
您正在组件中定义deleteUser
,User
但您正在尝试在App
它确实没有定义的情况下使用它。所以这个错误并不奇怪。
您遇到的问题之一是您的删除函数作用于一个不属于组件的数组(filteredUsers),因此即使您deleteUser
直接在组件内部调用,您也会得到另一个未定义的错误。
我在这里看到的是,从逻辑上讲,您希望将所有与单个用户打交道的逻辑保留在内部User
,但这样做您会采用将用户作为整体(数组)处理的逻辑,这是不一致的:用户为数组本身就是其中的一部分App
,为什么要将与数组相关的逻辑从它所属的地方取出?
在我看来,删除用户不是项目本身执行的功能,而是数组持有者执行的功能。因此,在您的情况下,您最好将其deleteUser
移至App
.
如果你这样做,用户组件将负责
- 显示单个用户
- 可能编辑单个用户
并且App将负责
- 显示用户列表
- 添加/删除所述列表的用户
推荐阅读
- templates - DotNet 模板:如何在不重复的情况下排除目录?
- javascript - 一步一步如何在 Rails 项目中包含 selectize.JS 构建 Ajax 请求和 Json 答案?
- regex - 使用正则表达式匹配不以 's 结尾的字符串
- angular - 错误:位置 652 处 JSON 中的意外标记]
- reactjs - 如何防止 Header 在登录屏幕上呈现?
- visual-studio - Visual Studio - 团队基础
- asp.net - 我无法创建 Azure 后端模板 VS 2019
- mysql - 分布式爬虫和一致性
- python - 如何在 Python 中加密有效负载以进行支付 - Adyen 支付网关
- python - 如何在 python 中解析 YAML 并将其中一些键输出到另一个 YAML