Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

在此练习中,在 App.svelte 中,我们忘记传递 PackageInfo.svelte 所需的 name prop,这意味着 <code> 元素为空并且 npm 链接已损坏。

¥In this exercise, in App.svelte we’ve forgotten to pass the name prop expected by PackageInfo.svelte, meaning the <code> element is empty and the npm link is broken.

我们可以通过添加 prop 来修复它...

¥We could fix it by adding the prop...

App
<PackageInfo
	name={pkg.name}
	version={pkg.version}
	description={pkg.description}
	website={pkg.website}
/>

...但由于 pkg 的属性对应于组件的预期 props,我们可以将它们 ‘spread’ 到组件上:

¥...but since the properties of pkg correspond to the component’s expected props, we can ‘spread’ them onto the component instead:

App
<PackageInfo {...pkg} />

相反,在 PackageInfo.svelte 中,你可以使用 rest 属性获取一个包含传递到组件中的所有 props 的对象...

¥[!NOTE] Conversely, in PackageInfo.svelte you can get an object containing all the props that were passed into a component using a rest property...

let { name, ...stuff } = $props();

...或者完全跳过 destructuring

¥...or by skipping destructuring altogether:

let stuff = $props();

...在这种情况下,你可以通过其对象路径访问属性:

¥...in which case you can access the properties by their object paths:

console.log(stuff.name, stuff.version, stuff.description, stuff.website);
上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
	import PackageInfo from './PackageInfo.svelte';
 
	const pkg = {
		name: 'svelte',
		version: 5,
		description: 'blazing fast',
		website: 'https://svelte.dev'
	};
</script>
 
<PackageInfo
	version={pkg.version}
	description={pkg.description}
	website={pkg.website}
/>