🌀 3.4 ライフサイクルフック(mounted, created, destroyed など)と this の関係


✅ 【要点】


🟢 【Vue の主なライフサイクルフック一覧】

タイミング フック名 何ができる?
作られる前 beforeCreate dataprops まだ使えない!
作られたあと created data / props / methods が使える
DOM に乗る直前 beforeMount まだ画面には表示されていない
DOM に乗ったあと mounted 画面が表示された後 → DOM操作できる
更新される直前 beforeUpdate データが変わるけど、画面はまだ変わってない
更新されたあと updated 画面もデータも変わったあと
消される直前 beforeDestroy コンポーネントが消える前
消されたあと destroyed コンポーネントが消えたあと

💡 Vue 2 系は destroyed / Vue 3 は unmounted


🟠 【クラスコンポーネントでの書き方】

@Component
export default class HelloWorld extends Vue {
  message: string = 'Hello';

  created() {
    console.log('Created!', this.message); // ← this 使える!
  }

  mounted() {
    console.log('Mounted!', this.message); // ← DOM も操作できる
  }

  beforeDestroy() {
    console.log('Before destroy');
  }

  destroyed() {
    console.log('Destroyed');
  }
}

どこで this が使える? 使える?
beforeCreate ❌ 使えない!
created ✅ 使える!
mounted ✅ 使える!
beforeDestroy ✅ 使える!
destroyed ✅ 使える!

🔧 【具体例:mounted で DOM にアクセスできる】

@Component
export default class Example extends Vue {
  count: number = 0;

  mounted() {
    const button = this.$el.querySelector('button');
    console.log('Button element:', button);
  }
}

🎯 this.$el で自分の DOM にアクセスできるのは mounted 以降。