LoginSignup
1
3

More than 3 years have passed since last update.

Vue.jsの動的コンポーネントについて

Posted at

Vue.jsの動的コンポーネントについて

動的コンポーネント

componentタグを使い、表示させるコンポーネントを動的に変化させる

    <button @click="currentComponent = 'Home'">Home</button>
    <button @click="currentComponent = 'About'">About</button>
    <component :is="currentComponent"></component>

    export default{
      data(){
        currentComponent:'Home'
      }
     }

ボタンクリックでcurrentComponentプロパティの値を変化させている。
componentタグのis属性の値により、描画されるコンポーネントを切り替えている。(ここではcurrentComponentの値がHomeならHomeコンポーネント、AboutならAboutコンポーネントが表示されるイメージ)

注意すべき挙動

コンポーネントが切り替わる際は、毎回毎回コンポーネントがdestroyされている。
コンポーネントを切り替えてもデータを保持していたいときにはkeep-aliveタグを使用する。

    <keep-alive>
      <component :is="currentComponent"></component>
    </keep-alive>

上記のようにkeep-aliveタグでcomponentタグを囲むことでコンポーネントを切り替えてもデータを保持することができる。
これはdestoryサイクルが発生していないからデータを保持することができるのだが、「destoryedされた際に発生させたい処理」、「createdされた際に発生させたい処理」を記述したい場合はもちろんあるだろう。
実はkeep-aliveタグを使った際にはdeactivated、activatedというライフサイクルができ、destoryedとcreatedの代わりをしてくれる。

1
3
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
1
3