Svelte 模版语法(一)

194 阅读2分钟

标签(Tags)

小写标记,如<div>,表示常规HTML元素。大写的标记(如<Widget><Namespace.Widget>)表示组件。

<script>
	import Widget from './Widget.svelte';
</script>

<div>
	<Widget/>
</div>

属性和道具(Attributes and props)

默认情况下,属性的工作方式与它们的HTML对应项完全相同。

<div class="foo">
	<button disabled>can't touch this</button>
</div>

在HTML中,值可以不加引号。

<input type=checkbox>

属性值可以包含JavaScript表达式。

<a href="page/{p}">page {p}</a>

或者它们可以是JavaScript表达式。

<button disabled={!clickable}>...</button>

如果布尔属性的值为truthy,则将其包含在元素中;如果值为falsy,则将其排除。

包含所有其他属性,除非其值为nullish(空或未定义)。

<input required={false} placeholder="This input field is not required">
<div title={null}>This div has no title attribute</div>

表达式可能包含会导致常规HTML中语法突出显示失败的字符,因此允许引用该值。引号不影响值的解析方式:

<button disabled="{number !== 42}">...</button>

当属性名和值匹配(name={name})时,可以用{name}替换它们。

<!-- These are equivalent -->
<button disabled={disabled}>...</button>
<button {disabled}>...</button>

扩展属性允许同时向元素或组件传递许多属性(attributes or properties )。

一个元素或组件可以有多个扩展属性,其中穿插着常规属性。

<Widget {...things}/>

(?props)引用传递给组件的所有道具,包括未使用export声明的道具。它在极少数情况下是有用的,但一般不推荐,因为Svelte很难优化。

<Widget {...$$props}/>

(?restProps)只包含未使用export声明的props。它可用于将其他未知属性传递给组件中的元素。

<input {...$$restProps}>