🟠 2.2 クラスと this のしくみ → Vue クラスコンポーネント理解の土台


✅ 【要点】


🟢 【クラスとは? → 「設計図」】

// クラス(設計図)
class User {
  name: string;

  constructor(name: string) {
    this.name = name; // ← このインスタンスの name
  }

  greet(): string {
    return `Hello, ${this.name}!`; // ← this はその人(インスタンス)
  }
}

// インスタンス(実物)を作る
const alice = new User('Alice');
console.log(alice.greet()); // "Hello, Alice!"

ことば 意味
class 設計図
constructor 最初に呼ばれる「組み立て工場」
this 今作っているその「実物」

🟣 【this が指すもの】

class Car {
  color: string;

  constructor(color: string) {
    this.color = color;
  }

  showColor() {
    console.log(`Color is ${this.color}`);
  }
}

const redCar = new Car('red');
redCar.showColor(); // "Color is red"

🟢 this.color → 今作った redCar の color

「誰のことを言っているか?」を決めるのが this


🟡 【Vue クラスコンポーネントと this

import { Vue, Component, Prop } from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
  @Prop() name!: string; // ← props も this につく

  count: number = 0;      // ← data も this につく

  increment(): void {     // ← method も this で呼ぶ
    this.count += 1;
  }

  get upperName(): string {  // ← computed も this を使う
    return this.name.toUpperCase();
  }
}

構成要素 書き方 どうアクセスする?
props @Prop() name!: string this.name
data count: number = 0 this.count
methods increment() this.increment()
computed get upperName() this.upperName
Vue の機能 this.$store, this.$emit $ がつくものも全部 this 経由

🎯 とにかく全部 this に乗る設計。