簡體   English   中英

如何僅在第一次條件為真時才保存變量

[英]How can I make variable save only the first time the condition is true

我有一個變量可以在overflow-x-auto時獲取滾動條的高度,並且我使用的是苗條的 javascript 框架。

為了解決這個問題,我使用了這段代碼:

<script>
  let hWith = 0;
  let hNot = 0;

  $: scrollBarHeight = hWith - hNot;
</script>

<div 
  bind:offsetHeight={hWith} 
  bind:clientHeight={hNot}
>
  my content...
</div>

並且工作正常並輸出: 17

問題是bind:總是會在每次重新渲染時觸發。

如您所知,滾動條不會神奇地改變大小,因此始終重新計算高度值並不重要

一旦我們得到 17 值(可能因瀏覽器而異),停止重新計算。


問題出在哪里?

問題是變量需要與$:
在開始時,
因為容器不會溢出,這意味着0

但是一旦我們得到一個大於 0 的數字。( returnedValue > 0
變量不再需要反應


我基本上希望當我保存scrollBarHeight (一個簡單的計算hWith - hNot )時,我不會再計算它了。

你知道我不喜歡我不能直接在一個變量而不是 3 中寫公式的事實。

with bind:它總是用新值設置變量。 (這可能效率低下,因為我的價值沒有太大變化)

let hWith = 0;
let hNot = 0;

$: scrollBarHeight = hWith - hNot;

✅ 像這樣的東西。

$: scrollBarHeight = if (div.offsetHeight - div.clientHeight > 0) {  
   // logic/code to make this variable not reactive anymore
   return div.offsetHeight - div.clientHeight;
}

為什么我需要它?

這個邏輯是一個孩子,而不是身體。 所以這就是為什么有些東西溢出了。 我需要這個值來糾正一些錯誤。

孩子的問題發生了很大變化並重新渲染,這可能會重新渲染並綁定很多值。

您可以只聲明一個常規變量並添加一個反應性語句而無需立即賦值。 例如

let scrollBarHeight = 0;

$: if (scrollBarHeight == 0 &&
       div.offsetHeight - div.clientHeight > 0) {
   scrollBarHeight = div.offsetHeight - div.clientHeight;
}

盡早打破反應性陳述可能會有所幫助

let counter = 0;
let evens = 0;
let threes = 0;

$: {
    if (counter < 10) {
        break $;
    }
    if (counter % 2 === 0) {
        evens++;
    }
}

$: {
    if (counter < 10) {
        break $;
    }
    if (counter % 3 === 0) {
        threes++;
    }
}

源代碼: https://svelte.dev/repl/be829d83edda4dd882b3b375f889745c?version=3.44.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM