【问题标题】:Svelte bind:offsetWidth with contextSvelte 绑定:offsetWidth 与上下文
【发布时间】:2020-07-09 17:22:02
【问题描述】:

这是我创建苗条上下文的方式:

<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>

【问题讨论】:

  • let layoutWidth = 0;
  • @HagaiWild nope

标签: svelte svelte-3 svelte-component


【解决方案1】:

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 来观察元素的大小......)。您可能希望将 resize 事件侦听器添加到 window 或达到此效果(还有一些库可以监视元素大小,但有些技巧)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多