根据有关 Props的Svelte 文档,我使用 props 将父组件的引用传递给子组件。
道具,“属性”的缩写,是您将数据从父组件向下传递到子组件的方式
这正是我想要做的。这是带有我的代码的 Svelte REPL,也在下面复制:
我的父母是App.html:
<div class='widget-container'>
<Widget foo bar="static" {baz}/>
</div>
<script>
import Widget from './Widget.html';
export default {
data: function(){
return {
baz: 'click me and check the console'
}
},
components: {
Widget
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
子组件是Widget.html:
<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>
<script>
export default {
oncreate: function(){
window.document.body.addEventListener('click', function(event){
console.log(`Clicked!, ${baz}`)
});
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
多亏了 props,HTML<p>元素可以清楚地引用父元素。但是,如何在子组件的 …
有没有办法在 Svelte 3 中绑定对象字段?
例子:
<script>
import MyComponent from "./MyComponent.svelte"
let myobjectID
</script>
<MyComponent bind:myobject[id]={myobjectID}>
<!-- Where myobject == {id: "123", name: "myName", and so on...} -->
Run Code Online (Sandbox Code Playgroud)
这可能吗?
我想警告用户在离开页面之前保存他的更改(表单更改)。如果他点击窗口上的任意位置,我想触发此警报。它可能是后退按钮或重新加载或页面上可用的任何导航链接。有人可以帮忙吗?
我正在开发一个小型 Svelte 应用程序,用于学习目的(我是 Svelte 新手)。该应用程序使用在视图中显示为 HTML 表格的对象数组:
let countries = [
{ code: "AF", name: "Afghanistan" },
{ code: "AL", name: "Albania" },
{ code: "IL", name: "Israel" }
];
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Code</th>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
{#if countries.length}
{#each countries as c, index}
<tr>
<td>{index+1}</td>
<td>{c.code}</td>
<td>{c.name}</td>
<td class="text-right">
<button data-code="{c.code}" on:click="{deleteCountry}" class="btn btn-sm btn-danger">Delete</button>
</td>
</tr>
{/each}
{:else}
<tr>
<td colspan="4">There are no countries</td>
</tr>
{/if}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
我正在这样进行删除操作:
function deleteCountry(){
let …Run Code Online (Sandbox Code Playgroud) 我正在 Svelte 方法的帮助下迭代 JSON onMount。我已将数据显示在表格中。
<script>
import { onMount } from "svelte";
const apiURL = "https://gist.githubusercontent.com/Goles/3196253/raw/9ca4e7e62ea5ad935bb3580dc0a07d9df033b451/CountryCodes.json";
let countries = [];
onMount(async function() {
const response = await fetch(apiURL);
countries = await response.json();
});
</script>
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Code</th>
</tr>
</thead>
<tbody>
{#if countries}
{#each countries as country }
<tr>
<td>{index + 1}</td>
<td>{country.name}</td>
<td>{country.code}</td>
</tr>
{/each}
{:else}
<p>There are no countries</p>
{/if}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
我无法做的是添加迭代计数列。使用{index + 1}。
我怎样才能得到想要的结果?