Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

App.svelte里我们忘了,当然是故意的,给PackageInfo设置name属性,也就意味着把<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. We could fix it by adding the prop...

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

但是,可但是啊小主,pkg的属性刚好是组件需要的。如此这般不如就散播了它吧:

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

App
<PackageInfo {...pkg} />

这样就不用一个一个属性写了,像虎妞好的坏的一股脑全给了祥子。

[!NOTE] 另外你也可以在PackageInfo.svelte使用...获取所有其余属性对象

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 altogether:

...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);

Edit this page on GitHub

previous next
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}
/>