获取 svelte 父节点尺寸

mar*_*lle 1 html css svelte

我正在尝试使用 Svelte,这是我第一次,很抱歉这个问题可能很愚蠢。我阅读了 Svelte 文档,但遇到了一个简单的问题。

基本上,我想获取组件的父尺寸(宽度和高度)。

例子:

<div>
  <MyNode />
</div>
Run Code Online (Sandbox Code Playgroud)

在里面MyNode我想要父级的尺寸div。我怎样才能做到这一点?

我试过这个:

<script lang="ts">
  import { onMount, tick } from 'svelte'

  let w = 0
  let h = 0
  console.log({ w, h })

  onMount(async () => {
    console.log('on mount')
    console.log({ w, h })
    // await tick()
  })
</script>

<main>
  <div class="flex w-screen h-screen">
    <div class="white w-150 min-w-150 h-full">side menu</div>

    <div
      class="bg-ligthGrey flex-grow h-full border border-orange-500"
      bind:clientWidth={w}
      bind:clientHeight={h}
    >
      content
    </div>
  </div>
</main>
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

在此输入图像描述

这仅在第一次打印(当然,它在 onMount 内部),如果我调整窗口大小,则不会发生任何变化。我需要w并且h始终更新。我能怎么做?

Cor*_*rrl 5

如果您使日志响应,$: console.log({ w, h })它将在每当wh更改时执行

为了让组件内的父 div 的尺寸,我将它们作为 prop REPL传递

<script>
    import MyNode from './MyNode.svelte'
    
    let w, h
</script>

<div bind:clientWidth={w} bind:clientHeight={h}>
    <MyNode parentWidth={w} parentHeight={h}/>
</div>

<style>
    div {
        background: lightblue;
    }
</style>
Run Code Online (Sandbox Code Playgroud)
MyNode.svelte
<script>
    export let parentWidth, parentHeight    
</script>

MyNode - parentWidth: {parentWidth} - parentHeight: {parentHeight}
Run Code Online (Sandbox Code Playgroud)

(请注意,parentWidthparentHeight最初将位于undefined组件内部 - 根据您计划基于它们执行的操作,应该对此进行处理)