點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-teleport to Control Element outside of x-data Block

Sam Xiao's Avatar 2022-01-13

Sometimes we want to control the HTML element but not in the x-data block. We can use <template> with x-teleport to teleport HTML to the block outside of x-data.

Version

Alpine 3.9

x-show

teleport000

By clicking the Toggle button, we can show or hide Hello World.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body>
    <div x-data="{ isShow: true }">
      <button @click="isShow = !isShow">Toggle</button>
      <div x-show="isShow">Hello World</div>
    </div>
  </body>
</html>

Line 10

<div x-data="{ isShow: true }">
  <button @click="isShow = !isShow">Toggle</button>
  <div x-show="isShow">Hello World</div>
</div>
  • <div> with x-data directive is controlled by Alpine
  • Hello World is shown by x-show directive

x-teleport

teleport000

Hello World is not in the x-data block. Can we control it by Alpine?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body>
    <div x-data="{ isShow: true }">
      <button @click="isShow = !isShow">Toggle</button>
      <template x-teleport="#greeting">
        <div x-show="isShow">Hello World</div>
      </template>
    </div>
    <div id="greeting" />
  </body>
</html>

Line 16

<div id="greeting"/>

Hello World is displayed here but not in any x-data block.

Line 10

<div x-data="{ isShow: true }">
  <button @click="isShow = !isShow">Toggle</button>
  <template x-teleport="#greeting">
    <div x-show="isShow">Hello World</div>
  </template>
</div>
  • We can embed our original Hello World with v-show in <template>
  • Use x-teleport with <template> to indicate following HTML would teleport to #greeting element

Conclusion

  • Always use x-teleport with <template> to teleport HTML to the block outside of x-data

Reference

Alpine, x-teleport