components - 在 Svelte 中创建可重用的模态组件的最佳实践?
问题描述
我一直无法理解在 Svelte 中创建可重用模态组件的最佳方法。我想拥有 Modal 组件,我可以在其中轻松地以可扩展的方式传递其他组件。当我单击背景时,它应该破坏模式和里面的内容。
我在这里创建了一个带有工作版本的 REPL,但想知道这是否是实现此目的的复杂方式: https ://svelte.dev/repl/9180dd40e7304fc78d175cf4535a6423?version=3.38.2
此方法有效,但我不知道这是否是建议的方法(我对 Svelte 和组件库都是新手)。
应用程序.js
<script>
import Modal from './Modal.svelte'
import Component1 from './Component1.svelte'
import Component2 from './Component2.svelte'
import {showModal} from './store.js'
let showC1, showC2 = false;
function toggleModal() {
$showModal = !$showModal;
}
function toggleC1() {
toggleModal();
showC1 = !showC1;
}
function toggleC2() {
toggleModal();
showC2 = !showC2;}
</script>
<button on:click={toggleC1}>
Toggle Component 1
</button>
<button on:click={toggleC2}>
Toggle Component 2
</button>
<Component1 {showC1} on:click={toggleC1} />
<Component2 {showC2} on:click={toggleC2} />
模态.svelte
<script>
import {showModal} from './store.js'
</script>
{#if $showModal}
<div on:click|self class='modal'>
<div class='content'>
<slot />
</div>
</div>
{/if}
<style>
.modal {
background-color: rgba(0, 0, 0, 0.589);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0.7;
display: flex;
justify-content: center;
align-items: center;
}
.content {
background-color: white;
width: 20em;
height: 20em;
}
</style>
Component1.svelte
<script>
import Modal from './Modal.svelte'
export let showC1;
</script>
{#if showC1}
<Modal on:click>
<div>
This is some content...
</div>
<button on:click>
close
</button>
</Modal>
{/if}
Component2.svelte
<script>
import Modal from './Modal.svelte'
export let showC2;
</script>
{#if showC2}
<Modal on:click>
<div>
...And some more content
</div>
<button on:click>
close
</button>
</Modal>
{/if}
store.js
import { writable } from "svelte/store";
export const showModal = writable(false);
解决方案
我想出了一个问题的答案:使用 svelte:component 制作动态组件。REPL 在这里: https ://svelte.dev/repl/4624e3f0f3684ddcb2e2da10592f6df1?version=3.38.2
推荐阅读
- .net - 如何模拟 Autofac.Multitenant.MultitenantContainer.ConfigureTenant
- python - Django 原子事务适用于 sqlite,但不适用于 postgresql
- fortran - netcdf fortran如何检索全局属性的总数
- mysql - 如何获取 MySQL 连续的时间戳差异?
- xml - 向 .asmx 服务 (VB.NET) 发送请求 (XML)
- google-sheets - GoogleSheets:ISBETWEEN 的数组参数大小不同。= 介于(11,$F3:F20,$G3:G20)
- ios - 不同的出口动作目的地属性有什么区别
- javascript - 是否可以使用 python 编写网站的后端,以便我可以调用 python 方法并显示其输出?
- python - 如何使用 N-Beats 算法和 pytorch 预测来预测 K 单变量时间序列?
- javascript - 有人可以解释一下这段代码的含义吗?