Issue
I'm making a tip calculator using vuejs 3 and typescript. I have 5 buttons with some values, I want to use their values to calculate a total, how do call the function tipPercentage so that it gives me a single numerical value which I can use to calculate the total, and also I can't add bill since it's a Ref type and not a number type. I'm using vue 3.2 script setup and typescript, open to javascript solution image of tip calculator app
<script lang="ts" setup>
import {ref} from 'vue'
let tips = [
{ id: 1, percent: 5},
{ id: 2, percent: 10},
{ id: 3, percent: 15},
{ id: 4, percent: 25},
{ id: 5, percent: 50},
]
const bill: number = ref(0)
let tipPercentageValue = (percentValue: number) => percentValue
const total: number = bill+ bill*tipPercentageValue(percentValue)
</script>
<h3>Bill</h3>
<input class="bill-input" type="number" v-model="bill" placeholder="enter bill" />
<h3>Select Tip %</h3>
<div class="tip-percent-buttons" >
<button class="percent-btn" v-for="tip in tips" :key="tip.id" @click="tipPercentageValue(tip.percent)" :value="tip.percent">
{{ tip.percent }}%
</button>
</template>
Solution
You have some problems in your code with the usage of ref. If you use the ref in your <script> and you want to assign a new value you need to add .value
https://v3.vuejs.org/guide/reactivity-fundamentals.html#creating-standalone-reactive-values-as-refs
Furthermore your tipPercantageValuefunction does nothing.
const selectedPercentage = ref(0)
const total = ref(0)
function percentageSelected(percentage: number) {
selectedPercentage.value = percentage
total.value = bill.value+ bill.value*selectedPercentage.value
}
like this total and billare reactive. Then use the percentageSelectedfunction as the @clickfunction
if you want the percentage to be in the 'correct' format add const computedPercantage = computed(() => selectedPercentage.value/100) and use it like
function percentageSelected(percentage: number) {
selectedPercentage.value = percentage
total.value = bill.value+ bill.value*computedPercantage.value
}
Answered By - Slin F
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.