Svelte 组件规范(二)

456 阅读1分钟

<script context="module">

带有context=“module”属性的<script>标记在模块首次求值时运行一次,而不是为每个组件实例运行一次。此块中声明的值可从常规<script>(和组件标记)访问,但反之亦然。

您可以从此块导出(export)绑定,它们将成为已编译模块的导出。

不能导出(export default)默认值,因为默认导出是组件本身。

<script context="module">
	let totalComponents = 0;

	// this allows an importer to do e.g.
	// `import Example, { alertTotal } from './Example.svelte'`
	export function alertTotal() {
		alert(totalComponents);
	}
</script>

<script>
	totalComponents += 1;
	console.log(`total number of times this component has been created: ${totalComponents}`);
</script>

在模块脚本中定义的变量不是被动的-重新分配它们不会触发重新提交程序,即使变量本身会更新。对于多个组件之间共享的值,请考虑使用存储

<style>

```<style>```块中的CSS将作用于该组件。

这是通过向受影响的元素添加一个类来实现的,该类基于组件样式的散列(例如svelte-123xyz)。

<style>
	p {
		/* this will only affect <p> elements in this component */
		color: burlywood;
	}
</style>

若要全局应用样式到选择器,请使用:global(…)修饰符。

<style>
	:global(body) {
		/* this will apply to <body> */
		margin: 0;
	}

	div :global(strong) {
		/* this will apply to all <strong> elements, in any
			 component, that are inside <div> elements belonging
			 to this component */
		color: goldenrod;
	}
</style>

如果要生成可全局访问的@keyframes,则需要在关键帧名称前面加上-global-。

编译时将删除-global-part,然后使用代码中其他地方的动画名称引用关键帧。

<style>
	@keyframes -global-my-animation-name {...}
</style>