具有上下文的 Svelte bind:offsetWidth

Svelte bind:offsetWidth with context

这是我创建 svelte 上下文的方法:

<script>
import {setContext} from 'svelte'
let layoutWidth


setContext('layout', {layoutWidth})

</script>
<div bind:offsetWidth={layoutWidth}><slot/></div>

如果我尝试在子组件中 getContext,那么我得到 undefined 但在父组件中 layoutWidth 始终具有值。

如何在 svelte 中获取父元素的 offsetHeight

我这样使用 getContext

<script>
import {getContext} from 'svelte'
const {layoutWidth} = getContext('layout')
$: console.log(layoutWidth) //undefined
</script>

Svelte 上下文不是 反应性的。该值在调用 setContext 时设置一次(您只能在组件初始化期间执行此操作),之后不会跟踪更改。

如果你确实需要传递一个反应值(即会改变),那么你需要通过上下文传递一个商店。

供应商示例:

<script>
  import { setContext } from 'svelte'
  import { writable } from 'svelte/store'

  const layoutWidth = writable(null)

  setContext('layoutWidth', layoutWidth)
</script>

<div bind:offsetWidth={$layoutWidth}><slot/></div>

消费者:

<script>
  import { getContext } from 'svelte'

  const layoutWidth = getContext('layoutWidth')

  // subscribe to the store to get the value
  // do this in a reactive expression to keep _layoutWidth in sync
  $: _layoutWidth = $layoutWidth

  // you can also write back to the store (if it's writable)
  $layoutWidth = 400
</script>

...

旁注:我怀疑 bind:offsetWidth 会做你想让它做的事。同样,该值只会被读取一次。调整 div 大小时不会更新该值(因为没有原生 API 来观察元素的大小...)。您可能想要向 window 添加一个 resize 事件侦听器或类似的东西(还有一些库可以通过一些技巧来监控元素大小)。