0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue.js teleport要素を使う

Last updated at Posted at 2022-05-14

表示する要素自体は一つのコンポーネントの中で管理したいが、表示自体はコンポーネントとは別の場所に表示したい。そんなときに使えるのが「teleport」要素。

teleport要素を使うシチュエーション

アプリの中にボタンがあり、そのボタンを押したときに別の要素を表示したい。なのでそれらをひとまとめにしたコンポーネントを作成したいが、表示する要素自体はボタンとは別の場所にしたい。このようなとき、「teleport」要素を利用すれば実現できる。

teleport要素の書き方

表示側

<body>
  <div id="app">
    <my-teleport /> <!-- teleport要素を記述するコンポーネント-->  
  </div>

  <!-- ここから --> 
  <div>
    テレポートとコンポーネントとの間の要素1
  </div>
  <div>
    テレポートとコンポーネントとの間の要素2
  </div>
  <!-- ここまではコンポーネントとteleport要素の間に表示される要素 -->

  <div id="teleport"></div> <!-- teleport要素を表示する場所 -->
</body>

コンポーネント側

Vue.createApp({})
  .component('my-teleport', {
    data: function() {
      return {
        show: false
      }
    },
    template: `
      <form>
        <input type="button" v-on:click="onclick(true)" value=" テレポート要素を表示する" />
      </form>

      <teleport to="#teleport">
        <div v-if="show">
          <p>テレポート!</p>
          <input type="button" v-on:click="onclick(false)" value="テレポート要素を非表示にする"/>
        </div>
      </teleport>
    `,
    methods: {
      onclick: function(event) {
        this.show = event
      }
    }
  })
  .mount('#app')

このように書くことでコンポーネントの中にあるteleport要素が二つのdivタグを跨いだ位置に表示できるようになる。さらに 「id=”app”」の外にも記述できる点もteleport要素の使いやすいところ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?