最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get html element of Svelte component using bind:this? - Stack Overflow

programmeradmin1浏览0评论

Suppose I have a reusable component called button.svelte,

<script>
export let text = undefined
</script>

<button>{text}</button>

Now I reuse this component in another component like so,

<script>
import { onMount } from "svelte"
import Button from "./Button.svelte"

let button

onMount(() => {
    console.log(button) // How do I print the html of the button element?
})
</script>

<Button text="Button" bind:this="{button}"></Button>

But button of bind:this doesn't seem to have the html of the button element. How do I get the html element of the button?

Suppose I have a reusable component called button.svelte,

<script>
export let text = undefined
</script>

<button>{text}</button>

Now I reuse this component in another component like so,

<script>
import { onMount } from "svelte"
import Button from "./Button.svelte"

let button

onMount(() => {
    console.log(button) // How do I print the html of the button element?
})
</script>

<Button text="Button" bind:this="{button}"></Button>

But button of bind:this doesn't seem to have the html of the button element. How do I get the html element of the button?

Share Improve this question asked Apr 30, 2021 at 13:10 AxelAxel 5,12118 gold badges75 silver badges146 bronze badges 3
  • Did you try innerHTML on button inside console.log? Also bind:this isn't supposed to be without double quotes? – the-juju Commented Apr 30, 2021 at 13:18
  • May be this can help : https://stackoverflow.com/questions/59889859/how-can-i-return-the-rendered-html-of-a-svelte-component – the-juju Commented Apr 30, 2021 at 13:19
  • @JulienGabriel I tried doing button.innerHTML but shows undefined – Axel Commented Apr 30, 2021 at 13:20
Add a comment  | 

1 Answer 1

Reset to default 16

To achieve this you have to do 2 things

  • bind element to prop using bind:this={prop}.

  • access the element in the parent component via the bonded prop and the important part is that you must do that in a reactive statement $:.

Button.svelte

<script>
    export let node
</script> 

<button bind:this={node}>
  <slot />
</button>

import Button component

<script>
    import Button from './Button.svelte'
    let button
    
    $:console.log(button)
</script>

<Button bind:node={button}>
    Hello
</Button>
发布评论

评论列表(0)

  1. 暂无评论