引用 Svelte 中的 "this" 组件

Reference to "this" component in Svelte

根据我的阅读,这似乎目前是不可能的:https://github.com/sveltejs/svelte/pull/4523#issuecomment-596232030

我想构建一个树结构,并想在树的任意位置高亮显示活动节点。如果我使用商店来 write/read 当前活动的节点 ID,这很简单,只需检查 ID 是否与组件的匹配。

但如果我有数千个节点,恐怕这可能会变得很慢,因为每个节点都会在当前 ID 更改时进行检查。

所以我想我可以改为存储对当前活动节点的引用,这样我就可以轻松 deactivate/activate 任何节点。例如:

import { activeNode } from './stores'

let active = false

export function activate() {
  $activeNode.deactivate()
  activeNode.set(this) // <- this is undefined
  active = true
}

export function deactivate() {
  active = false
}

我相信这样的事情会快得多,因为我可以根据需要在任何节点上调用 activate 方法。

那么如何引用组件实例呢?或者有更好的方法吗?

您可以使用 eval 非常骇人听闻地访问 this(不要这样做),或者非常骇人听闻地与父组件同谋 (bind:this)...但是你不需要。

暴露外部世界所需要的东西怎么样?

<script>
    import { activeNode } from './stores.js'

    let active = false

    const api = {
        activate() {
            if ($activeNode) $activeNode.deactivate()
            $activeNode = api // sugar for: activeNode.set(api)
            active = true
        },
        deactivate() {
            active = false
        }
    }
</script>

<div class:active>
    Node
</div>

<style>
    .active {
        font-weight: bold;
    }
</style>