mounted
, created
, destroyed
など)と this
の関係this
が必ず使える(props / data / methods すべて)this.name
, this.count
, this.increment()
などが安全に使えるタイミングタイミング | フック名 | 何ができる? |
---|---|---|
作られる前 | beforeCreate |
data や props まだ使えない! |
作られたあと | 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 |
✅ 使える! |
@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 以降。