0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue.js の computed プロパティの使い方

Posted at

はじめに

Vue.js では、テンプレートの中でデータを動的に計算するために computed プロパティを使用します。本記事では computed プロパティの基本的な使い方と、その活用例について詳しく解説します。


1. computed プロパティとは?

computed プロパティは、Vue のテンプレート内で使用する計算済みの値を作成するためのプロパティです。methods とは異なり、キャッシュ されるため、依存しているデータが変更されたときにのみ再計算されます。


2. 基本的な使い方

以下の例では、firstNamelastName から fullName を計算する computed プロパティを作成します。

<template>
  <div>
    <p>First Name: {{ firstName }}</p>
    <p>Last Name: {{ lastName }}</p>
    <p>Full Name: {{ fullName }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    };
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
};
</script>

実行結果

First Name: John
Last Name: Doe
Full Name: John Doe

3. computed と methods の違い

computedmethods はどちらもテンプレート内で使用できますが、動作が異なります。

比較項目 computed methods
キャッシュ あり(依存データが変わるまで再計算しない) なし(呼び出すたびに計算)
パフォーマンス 高い(不要な計算を避ける) 低い(毎回再計算する)

例: computedmethods を使った fullName の比較

<script>
export default {
  data() {
    return {
      firstName: 'Jane',
      lastName: 'Smith'
    };
  },
  computed: {
    computedFullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  },
  methods: {
    methodFullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
};
</script>

テンプレート内で以下のように使用した場合:

<p>Computed Full Name: {{ computedFullName }}</p>
<p>Method Full Name: {{ methodFullName() }}</p>

computedFullNamefirstNamelastName が変わるまでキャッシュされますが、methodFullName()毎回呼び出されるたびに計算 されます。


4. setter を使った computed プロパティ

通常の computed プロパティは「getter」のみですが、setter を追加すると、値を変更することもできます。

<template>
  <div>
    <input v-model="fullName" />
    <p>First Name: {{ firstName }}</p>
    <p>Last Name: {{ lastName }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      firstName: 'Alice',
      lastName: 'Brown'
    };
  },
  computed: {
    fullName: {
      get() {
        return `${this.firstName} ${this.lastName}`;
      },
      set(newValue) {
        const parts = newValue.split(' ');
        this.firstName = parts[0] || '';
        this.lastName = parts[1] || '';
      }
    }
  }
};
</script>

この場合、fullName の値を input に入力すると、firstNamelastName も更新されます。


5. computed の応用例

配列をフィルタリングする

<template>
  <div>
    <input v-model="searchQuery" placeholder="検索" />
    <ul>
      <li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Cherry' }
      ]
    };
  },
  computed: {
    filteredItems() {
      return this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    }
  }
};
</script>

このように computed を使うことで、リアルタイム検索機能を簡単に実装できます。


6. まとめ

  • computed プロパティは 依存するデータが変化したときのみ再計算される
  • methods と異なり キャッシュされる ため、不要な計算を減らしパフォーマンスが向上する。
  • computedsetter を定義すると、データを双方向に変更可能。
  • 配列のフィルタリングなど、動的なデータ処理に適している。

これで computed プロパティの基本的な使い方が理解できました! Vue.js を活用して、効率的なデータ操作を行いましょう。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?