[英]Svelte bind:offsetWidth with context
This is a how I create svelte context:这是我创建苗条上下文的方式:
<script>
import {setContext} from 'svelte'
let layoutWidth
setContext('layout', {layoutWidth})
</script>
<div bind:offsetWidth={layoutWidth}><slot/></div>
If I try to getContext
in children component, then i got undefined
but in parent component layoutWidth always has value.如果我尝试
getContext
儿童组件,然后我undefined
,但在父组件layoutWidth总是具有价值。
How to get offsetHeight
of parent element in svelte?如何在svelte中获取父元素的
offsetHeight
?
I use getContext
like this:我像这样使用
getContext
:
<script>
import {getContext} from 'svelte'
const {layoutWidth} = getContext('layout')
$: console.log(layoutWidth) //undefined
</script>
Svelte context is not reactive. Svelte 上下文不是反应性的。 The value is set once when
setContext
is called (which you can do only during component initialization), and it is not tracked for changes afterward.该值在调用
setContext
时设置一次(您只能在组件初始化期间执行此操作),之后不会跟踪更改。
If you do need to pass a reactive value (ie that will change), then you need to pass a store through context.如果您确实需要传递一个反应值(即会改变),那么您需要通过上下文传递一个存储。
Example provider:示例提供程序:
<script>
import { setContext } from 'svelte'
import { writable } from 'svelte/store'
const layoutWidth = writable(null)
setContext('layoutWidth', layoutWidth)
</script>
<div bind:offsetWidth={$layoutWidth}><slot/></div>
And the consumer:而消费者:
<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>
...
Side note: I doubt bind:offsetWidth
will do what you want it to do.旁注:我怀疑
bind:offsetWidth
会做你想做的事。 Here again, the value will be read only once.同样,该值将仅读取一次。 The value won't be updated when the div is resized ('cause there's no native API to watch elements' size...).
当 div 调整大小时,该值不会更新(因为没有原生 API 来观察元素的大小......)。 You'll probably want to add a
resize
event listener to window
or something to this effect (there also exists some libs that enable watching elements size, with some trickery).您可能希望向
window
添加一个resize
事件侦听window
或其他类似的东西(还有一些库可以使用一些技巧来观察元素大小)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.