LoginSignup
16
13

More than 5 years have passed since last update.

Vue.js 算出プロパティ(computed)でクラスを作るテクニック

Last updated at Posted at 2017-06-19

はじめに

vue.jsの算出プロパティ(computed)を利用して、内部クラスっぽいものを作るという
裏技的な利用例を紹介します

以下の例は、身長・体重の値から、BMIと血液量を算出し、表示するプログラムです。
算出プロパティは一般的に値やプレーンオブジェクトを返り値としますが
ここでは health の返り値を 関数を含んだオブジェクト にしています。

<body>
    <div id="app">
        <ul>
            <li>身長 : {{height}} cm</li>
            <li>体重 : {{weight}} kg</li>
            <li>BMI : {{health.getBmi()}}</li>
            <li>血液量 : {{health.getBloodVolume()}} kg</li>
        </ul>
    </div>
    <script>
        var vueOption = {
            el : '#app',
            data : {
                height : 165, // 身長(cm)
                weight : 63   // 体重(kg)
            },
            computed : {
                // 詳細情報算出クラス
                health : function(){
                    var _this = this;
                    return {
                        // BMIを算出
                        getBmi : function(){
                            var h = _this.height / 100;
                            return _this.weight / ( h * h );
                        },
                        // 血液量を算出
                        getBloodVolume : function(){
                            return _this.weight / 13;
                        }
                    }
                }
            },
        };
        var app = new Vue(vueOption);
    </script>
</body>

実行結果

テンプレート上で {{health.getBmi()}} {{health.getBloodVolume()}} と記載した部分に
計算結果が出力される

image.png

使い道あるの?

現時点では思いつかないです

  • 複数のメソッドをある名前空間(health)の元に記載したい
  • 一部の関数をあるオブジェクト(health)の元にネストさせたい
  • vueオブジェクト内でメソッドチェーンを作りたい
  • (コンポーネントシステムを使わない場合)肥大化しがちなメソッドを分割して管理したい

(ちなみに、methods はこのような使い方はできないです)

おわりに

もし有用な使い方を見つけたら教えてください

「いいね」していただけると嬉しいです!

16
13
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
16
13