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
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>
withx-data
directive is controlled by AlpineHello World
is shown byx-show
directive
x-teleport
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
withv-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 ofx-data