Skip to main content

运行时

svelte

svelte 包暴露了 生命周期函数上下文 API

The svelte package exposes lifecycle functions and the context API.

onMount

导出片段: svelte#onMount

onMount 函数安排回调在组件安装到 DOM 后立即运行。 它必须在组件初始化期间调用(但不需要位于组件内部;可以从外部模块调用它)。

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live inside the component; it can be called from an external module).

onMount 不在 服务器端组件 内运行。

onMount does not run inside a server-side component.

<script>
	import { onMount } from 'svelte';

	onMount(() => {
		console.log('the component has mounted');
	});
</script>

如果从 onMount 返回一个函数,则在卸载组件时将调用该函数。

If a function is returned from onMount, it will be called when the component is unmounted.

<script>
	import { onMount } from 'svelte';

	onMount(() => {
		const interval = setInterval(() => {
			console.log('beep');
		}, 1000);

		return () => clearInterval(interval);
	});
</script>

仅当传递给 onMount 的函数同步返回值时,此行为才会起作用。 async 函数始终返回 Promise,因此无法同步返回函数。

beforeUpdate

导出片段: svelte#beforeUpdate

安排回调在任何状态更改后更新组件之前立即运行。

Schedules a callback to run immediately before the component is updated after any state change.

回调第一次运行将在初始 onMount 之前

<script>
	import { beforeUpdate } from 'svelte';

	beforeUpdate(() => {
		console.log('the component is about to update');
	});
</script>

afterUpdate

导出片段: svelte#afterUpdate

安排回调在组件更新后立即运行。

Schedules a callback to run immediately after the component has been updated.

回调第一次运行将在初始 onMount 之后

<script>
	import { afterUpdate } from 'svelte';

	afterUpdate(() => {
		console.log('the component just updated');
	});
</script>

onDestroy

导出片段: svelte#onDestroy

安排回调在组件卸载之前立即运行。

Schedules a callback to run immediately before the component is unmounted.

onMountbeforeUpdateafterUpdateonDestroy 中,这是唯一一个在服务器端组件内运行的组件。

Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component.

<script>
	import { onDestroy } from 'svelte';

	onDestroy(() => {
		console.log('the component is being destroyed');
	});
</script>

tick

导出片段: svelte#tick

返回一个 promise,一旦应用了任何挂起的状态更改,该 promise 就会解决;如果没有,则在下一个微任务中解决。

Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.

<script>
	import { beforeUpdate, tick } from 'svelte';

	beforeUpdate(async () => {
		console.log('the component is about to update');
		await tick();
		console.log('the component just updated');
	});
</script>

setContext

导出片段: svelte#setContext

将任意 context 对象与当前组件和指定的 key 关联并返回该对象。 然后上下文可用于具有 getContext 的组件的子级(包括分槽内容)。

Associates an arbitrary context object with the current component and the specified key and returns that object. The context is then available to children of the component (including slotted content) with getContext.

与生命周期函数一样,必须在组件初始化期间调用它。

Like lifecycle functions, this must be called during component initialisation.

<script>
	import { setContext } from 'svelte';

	setContext('answer', 42);
</script>

上下文本质上并不是反应性的。 如果你需要上下文中的反应性值,那么你可以将存储传递到上下文中,这将是反应性的。

getContext

导出片段: svelte#getContext

检索属于具有指定 key 的最近父组件的上下文。 必须在组件初始化期间调用。

Retrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation.

<script>
	import { getContext } from 'svelte';

	const answer = getContext('answer');
</script>

hasContext

导出片段: svelte#hasContext

检查是否已在父组件的上下文中设置给定的 key。 必须在组件初始化期间调用。

Checks whether a given key has been set in the context of a parent component. Must be called during component initialisation.

<script>
	import { hasContext } from 'svelte';

	if (hasContext('answer')) {
		// do something
	}
</script>

getAllContexts

导出片段: svelte#getAllContexts

检索属于最近父组件的整个上下文映射。 必须在组件初始化期间调用。 例如,如果你以编程方式创建组件并希望将现有上下文传递给它,则很有用。

Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.

<script>
	import { getAllContexts } from 'svelte';

	const contexts = getAllContexts();
</script>

createEventDispatcher

导出片段: svelte#createEventDispatcher

创建可用于调度 组件事件 的事件调度程序。 事件调度程序是可以接受两个参数的函数: namedetail

Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.

使用 createEventDispatcher 创建的组件事件会创建 CustomEvent。 这些事件不属于 bubbledetail 参数对应于 CustomEvent.detail 属性,并且可以包含任何类型的数据。

Component events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.

<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();
</script>

<button on:click={() => dispatch('notify', 'detail value')}>Fire Event</button>

从子组件分派的事件可以在其父组件中监听。 分派事件时提供的任何数据都可在事件对象的 detail 属性上使用。

Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the detail property of the event object.

<script>
	function callbackFunction(event) {
		console.log(`Notify fired! Detail: ${event.detail}`);
	}
</script>

<Child on:notify={callbackFunction} />

可以通过将第三个参数传递给调度函数来取消事件。 如果使用 event.preventDefault() 取消事件,则该函数返回 false,否则返回 true

Events can be cancelable by passing a third parameter to the dispatch function. The function returns false if the event is cancelled with event.preventDefault(), otherwise it returns true.

<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();

	function notify() {
		const shouldContinue = dispatch('notify', 'detail value', { cancelable: true });
		if (shouldContinue) {
			// no one called preventDefault
		} else {
			// a listener called preventDefault
		}
	}
</script>

你可以键入事件调度程序来定义它可以接收哪些事件。 这将使你的代码在组件内(错误调用被标记)和使用组件时(事件类型现在已缩小)更加类型安全。 请参阅 here 如何操作。

You can type the event dispatcher to define which events it can receive. This will make your code more type safe both within the component (wrong calls are flagged) and when using the component (types of the events are now narrowed). See here how to do it.

类型(Types)

类型: svelte

上一页 特殊元素
下一页 svelte/store