如何将 querySelector 范围限定为 Svelte 中的组件?

Ant*_*ine 2 svelte svelte-component

我有这个组件,并且我想以状态驱动的方式不可行的方式对其子元素进行一些操作。所以我想在其中使用一个语句和一个querySelector。但是我怎样才能将它的范围限定到元素呢?页面中有组件的多个实例,因此无法使用类或 id。我怎样才能做到这一点?

这是一个简化的代码:

    <script>
      export let value = ''
      export let readonly = true

      $: if (value && !readonly){
      // selects the first element in the document, not the one from this instance 
      const nd = document.querySelector('.forminput')
      // Do something with nd
    }
   </script>

    <textarea bind:value wrap="soft" rows="1" class="forminput"></textarea>
Run Code Online (Sandbox Code Playgroud)

Vik*_*how 10

基于 Stephane Vanraes 的答案,使用bind:this将组件的顶级元素绑定到变量,然后在该根元素上使用querySelectorand 。querySelectorAll例如:

<script>
  import { onMount } from 'svelte';
  let root;
  let text;
  let value;

  onMount(() => {
     const nd = root.querySelectorAll('.forminput');
     // Do something with nd, such as adding event listeners, styles, etc.
  });
</script>

<div bind:this={root}>
  <input type="text" bind:value class="forminput"/>
  <textarea bind:text wrap="soft" rows="1" class="forminput"></textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

然后,您可以获得querySelector组件范围的全部功能。

请注意,root只有在组件安装后才正确绑定,从而将代码封装在函数中onMount


Ste*_*aes 6

您可以使用bind:this将元素分配给变量

<script>
   let wrapper;
</script>

<div bind:this="{wrapper}"></div>
Run Code Online (Sandbox Code Playgroud)

现在你可以wrapper像从 querySelector 中得到它一样使用