I'm currently working on a Vue 3 component using the Composition API that fetches values from a JSON object and displays them on the screen. The component reads data from a local data.json file and returns these values to the template. The JSON file consists of a single object with multiple values, and my goal is to round each value to the nearest whole number using Math.round(). To achieve this, I've created a computed property that rounds the values as follows:
const data = ref({})
const roundedData = computed(() => roundedValue())
const getData = async() => {
try {
const res = await axios.get('data.json')
data.value = res.data
console.log(data.value)
} catch(error) {
console.log(error)
}
}
onMounted(() => {
getData()
})
const roundedValue = () => {
return Math.round(data.value)
}
However, the current setup doesn't round the individual values (val, val2, val3, val4) within the object. How can I use Math.round() or Math.toFix(2) to collectively round all the returned values from data.json?
Here's the remaining code:
Component (with Tailwindcss):
<template>
<div>
<div class="px-4 py-6 sm:px-0">
<div class="bg-white shadow overflow-hidden sm:rounded-lg">
<div class="border-t border-gray-200">
<dl>
<div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt class="text-sm font-medium text-gray-500">Value One</dt>
<dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val }}</dd>
</div>
<div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt class="text-sm font-medium text-gray-500">Value Two</dt>
<dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val2 }}</dd>
</div>
<div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt class="text-sm font-medium text-gray-500">Value Three</dt>
<dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val3 }}</dd>
</div>
<div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt class="text-sm font-medium text-gray-500">Value Four</dt>
<dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val4 }}</dd>
</div>
</dl>
</div>
</div>
</div>
</div>
</template>
<script>
import { onMounted, ref, computed } from 'vue'
import axios from 'axios'
export default {
setup() {
const data = ref({})
const roundedData = computed(() => roundedValue())
const getData = async() => {
try {
const res = await axios.get('data.json')
data.value = res.data
console.log(data.value)
} catch(error) {
console.log(error)
}
}
onMounted(() => {
getData()
})
const roundedValue = () => {
return Math.round(data.value)
}
return {
data,
roundedData
}
}
}
</script>
Data.json:
{
"val": 1.446565,
"val2": 45.678,
"val3": 56.75,
"val4": 78.98
}