LoginSignup
11
3

More than 1 year has passed since last update.

[Vue] 親子間のライフサイクルフック(created, mounted)の処理順

Last updated at Posted at 2021-11-13

はじめに

  • 機能実装に伴って、mountedライフサイクルフックに処理を追加した際に、思い通りの挙動をせず解決までにちょっと時間をかけてしまったので自戒の念を込めまとめます。

やりたかったこと

  • 前提として、親のmountedで取得したデータを受け取って要素を表示するコンポーネント
  • その要素に対して処理を追加したい

結論

  • 単純に親子間の処理順の問題でした。(ただの無知でした)
  • 親のmountedより子のmountedが先に処理される為、思い通りの挙動にならなかったということです。

サンプル

親コンポーネント

Parent.vue
<template>
  <div>
    <span>parent</span>
    <Child />
  </div>
</template>

<script>
import Child from './Child.vue'

export default {
  components: {
    Child,
  },
  mounted() {
    console.log("i am parent.")
  },
}
</script>

子コンポーネント

Child.vue
<template>
  <div>
    <span>child</span>
  </div>
</template>

<script>
export default {
  mounted() {
    console.log("i am child.")
  }
}
</script>

結果

スクリーンショット 2021-11-13 17.10.37.png

サンプル改

  • 孫コンポーネントを追加
  • createdライフサイクルフックを追加

親コンポーネント

Parent.vue
<template>
  <div>
    <span>parent</span>
    <Child />
  </div>
</template>

<script>
import Child from './Child.vue'

export default {
  components: {
    Child,
  },
  created() {
    console.log("[created] i am parent.")
  },
  mounted() {
    console.log("[mounted] i am parent.")
  },
}
</script>

子コンポーネント

Child.vue
<template>
  <div>
    <span>child</span>
    <Grandchild />
  </div>
</template>

<script>
import Grandchild from './Grandchild.vue'

export default {
  components: {
    Grandchild,
  },
  created() {
    console.log("[created] i am child.")
  },
  mounted() {
    console.log("[mounted] i am child.")
  }
}
</script>

孫コンポーネント

Grandchild.vue
<template>
  <div>
    <span>grand child</span>
  </div>
</template>

<script>
export default {
  created() {
    console.log("[created] i am grand child.")
  },
  mounted() {
    console.log("[mounted] i am grand child.")
  }
}
</script>

結果

スクリーンショット 2021-11-13 17.15.20.png

まとめ

  • createdは、親→子の順に処理が行われる
  • mountedは、子→親の順に処理が行われる
  • めんどくさがらず仕組みを理解しよう!
    • こういうディティールへの理解が大事だなと自戒

参考記事

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