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

明智如你,应该不会整个应用就整一个组件吧?贴心的Svelte也想到了,我们可以从其它文件中引入组件并在标签中使用它们,以此支持组合多个组件

It would be impractical to put your entire app in a single component. Instead, we can import components from other files and include them in our markup.

首先在文件App.svelte的顶部添加<script>标签并引入Nested.svelte

Add a <script> tag to the top of App.svelte that imports Nested.svelte...

App
<script>
	import Nested from './Nested.svelte';
</script>
<script lang="ts">
	import Nested from './Nested.svelte';
</script>

接下来就可以在标签中使用<Nested>组件了

...and include a <Nested /> component:

App
<p>This is a paragraph.</p>
<Nested />

注意看:虽然在Nested.svelte中也有个<p>元素但App.svelte中的样式并没有影响到它。

Notice that even though Nested.svelte has a <p> element, the styles from App.svelte don’t leak in.

为了区别于HTML原生元素,组件的标签名称采用首字母大写. [!NOTE] Component names are capitalised, to distinguish them from HTML elements.

Edit this page on GitHub

previous next
1
2
3
4
5
6
7
8
9
10
<p>This is a paragraph.</p>
 
<style>
	p {
		color: goldenrod;
		font-family: 'Comic Sans MS', cursive;
		font-size: 2em;
	}
</style>