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?

More than 1 year has passed since last update.

【Vue.js3】computed(getter)とmethods(setter)の違い

Last updated at Posted at 2023-06-27

結果

image.png

index
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
    <div id="app">
        <p>{{ message.split('').reverse().join('') }}</p>
        <p>{{ reversedMessage }}</p>
        <p>{{ reversedMessageMethod() }}</p>
    </div>

    <script src="https://unpkg.com/vue@3.1.5"></script>
    <script src="js/main.js"></script>
</body>
</html>
main.js
const app = Vue.createApp({
    data: () => ({
        message: 'Hello Vue.js!'
    }),
    computed: {
        reversedMessage: function() {
            return this.message.split('').reverse().join('')
        }
    },
    methods: {
        reversedMessageMethod: function() {
            return this.message.split('').reverse().join('')
        }
    }
}).mount('#app')

data、computed。methodsで同じ結果が得られるプログラムを用意しました。

computed

・算出プロパティ
・htmlファイルで呼び出すときに、()が不要

<p>{{ reversedMessage }}</p>

・getterとsetterが定義できる
・キャッシュ有り(依存関係に基づきキャッシュされるため)
→処理を高速化

getter

プロパティの値を取得するための関数です。プロパティにアクセスするときにゲッターが呼び出され、その返り値が参照されます。ゲッターは、データの加工や計算を行うために使用されることがあります。

// ゲッターの定義
getters: {
  formattedMessage: function() {
    return this.message.toUpperCase();
  }
},

methods

・メソッド
・htmlファイルで呼び出すときに、()が必要

<p>{{ reversedMessageMethod() }}</p>

・getterしか定義できない
・キャッシュ無し(呼び出されるたびに処理を行い、結果を返すため)

setter

プロパティの値を設定するための関数です。プロパティに値を代入するときにセッターが呼び出され、その引数として渡された値を使用してプロパティの値を更新します。セッターは、プロパティの値の変更時に追加のロジックを実行するために使用されることがあります。

setters: {
  setMessage: function(value) {
    this.message = value.trim();
  }
}
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?