体重、身長を入力して、ボタンを押すとBMI値が計算されるシンプルな仕組みです。
概要
BMIは以下の式で算出できます。
BMI = 体重 ÷ (身長 x 2 )
今回のサンプルでは、この体重と身長を入力すると、この計算式でBMIを計算するようにします。
実際のサンプルはこちら
サンプルコード
<template>
  <div class="bmi-maker">
    <div><input v-model="weight" type="text" placeholder="体重">Kg</div>
    <div><input v-model="height" type="text" placeholder="身長">Cm</div>
    <div><button @click="calculate">計算する</button></div>
    <div v-if="result">結果:{{result}}</div>
    <div v-if="err">{{err}}</div>
  </div>
</template>
<script>
export default {
  name: 'bmi-maker',
  data(){
    return{
      weight: '',
      height: '',
      result: '',
      err: '',
    }
  },
  methods:{
    calculate(){
      //BMI = 体重kg ÷ (身長m)2
      //身長をセンチで入力しているので、100で割る
      if(this.weight && this.height){
        this.height = this.height / 100
        this.result = this.weight / (this.height * this.height)
        this.err= ''
      }else{
        this.err = "体重と身長を入力してください!"
      }
    }
  }
}
</script>
<style scoped>
.bmi-maker{
  max-width: 1000px;
  margin:auto;
}
</style>
解説
「計算する」ボタンを押したらmethodsのcalculate()が反応します。
calculate(){
      //BMI = 体重kg ÷ (身長m)2
      //身長をセンチで入力しているので、100で割る
      if(this.weight && this.height){
        this.height = this.height / 100
        this.result = this.weight / (this.height * this.height)
        this.err= ''
      }else{
        this.err = "体重と身長を入力してください!"
      }
    }
もし体重と身長を入力していない場合は計算されずにエラーを返します。
非常にシンプルなコードです。
コードで計算する方法のイメージをつかんでください。
  
  
  
  


コメント