Vue.jsで作ったBMI計算機のサンプルコードです。
対象者は、Vueでハローワールドまで出せて、そのあと色々サンプルコードいじってみたい人です。
体重、身長を入力して、ボタンを押すとBMI値が計算されるシンプルな仕組みです。逆に、この仕組みだけのコードなので、構造がシンプルで初心者向けに理解しやすくなっています。
実際に動作はこちらで確認できます。
(このサイトは、VueとFirebaseに特化したサンプルコード集にしていく予定です。詳しくはブログで)
サンプルコード
<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>
(追記8/19 BMIの計算式を間違えていましたの訂正しました。)
ポイントは、「計算する」ボタンを押したらmethodsのcalculate()が反応するところです。
「@click」はvueの「v-on:click」の省略方法です。よく見かけるはずなので覚えておいて損はないでしょう。
参考:
イベントハンドリング