Context
上下文允许组件访问父组件拥有的值,而无需将它们作为 props 传递下来(可能通过许多中间组件层,称为’prop-drilling’)。父组件使用setContext(key, value)设置上下文...
<script>
import { setContext } from 'svelte';
setContext('my-context', 'hello from Parent.svelte');
</script><script lang="ts">
import { setContext } from 'svelte';
setContext('my-context', 'hello from Parent.svelte');
</script>...并且孩子使用getContext检索它:
<script>
import { getContext } from 'svelte';
const message = getContext('my-context');
</script>
<h1>{message}, inside Child.svelte</h1><script lang="ts">
import { getContext } from 'svelte';
const message = getContext('my-context');
</script>
<h1>{message}, inside Child.svelte</h1>这在Parent.svelte不直接了解Child.svelte时尤其有用,而是将其作为children片段(演示)的一部分进行渲染:
<Parent>
<Child />
</Parent>关键(如示例中所示 'my-context')和上下文本身可以是任何 JavaScript 值。
除了 setContext 和 getContext,Svelte 还暴露了 hasContext 和 getAllContexts 函数。
使用上下文与状态
您可以将响应式状态存储在上下文中(demo)...
<script>
import { setContext } from 'svelte';
import Child from './Child.svelte';
let counter = $state({
count: 0
});
setContext('counter', counter);
</script>
<button onclick={() => counter.count += 1}>
increment
</button>
<Child />
<Child />
<Child />...尽管请注意,如果您不是更新而是重新分配 计数器counter,您将“断开链接”——换句话说,不是这个...
<button onclick={() => counter = { count: 0 }}>
reset
</button>...你必须这样做:
<button onclick={() => counter.count = 0}>
reset
</button>Svelte 会警告你如果做错了。
类型安全的上下文
一种有用的模式是将对 setContext 和 getContext 的调用封装在辅助函数中,这样您可以保留类型安全:
import { function getContext<T>(key: any): TRetrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
getContext, function setContext<T>(key: any, context: T): TAssociates 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.
setContext } from 'svelte';
const const key: {}key = {};
/** @param {User} user */
export function function setUserContext(user: User): voidsetUserContext(user: Useruser) {
setContext<User>(key: any, context: User): UserAssociates 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.
setContext(const key: {}key, user: Useruser);
}
export function function getUserContext(): UsergetUserContext() {
return /** @type {User} */ (getContext<User>(key: any): UserRetrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
getContext(const key: {}key));
}import { function getContext<T>(key: any): TRetrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
getContext, function setContext<T>(key: any, context: T): TAssociates 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.
setContext } from 'svelte';
const const key: {}key = {};
export function function setUserContext(user: User): voidsetUserContext(user: Useruser: User) {
setContext<User>(key: any, context: User): UserAssociates 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.
setContext(const key: {}key, user: Useruser);
}
export function function getUserContext(): UsergetUserContext() {
return getContext<User>(key: any): UserRetrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
getContext(const key: {}key) as User;
}替换全局状态
当你有多个不同组件共享的状态时,你可能想将其放入自己的模块中,并在需要的地方导入它:
export const const myGlobalState: {
user: {};
}
myGlobalState = function $state<{
user: {};
}>(initial: {
user: {};
}): {
user: {};
} (+1 overload)
namespace $state
$state({
user: {}user: {
// ...
}
// ...
});在许多情况下这完全没问题,但存在风险:如果在服务器端渲染期间修改状态(虽然不推荐,但完全可能!)...
<script>
import { myGlobalState } from './state.svelte.js';
let { data } = $props();
if (data.user) {
myGlobalState.user = data.user;
}
</script><script lang="ts">
import { myGlobalState } from './state.svelte.js';
let { data } = $props();
if (data.user) {
myGlobalState.user = data.user;
}
</script>...然后数据可能被下一个用户通过next访问。上下文解决了这个问题,因为它不会在请求之间共享。
Edit this page on GitHub llms.txt