Svelte基础
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
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 thename
prop expected byPackageInfo.svelte
, meaning the<code>
element is empty and the npm link is broken. We could fix it by adding the prop...
<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:
<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);
<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}
/>