我正在嘗試使用 CompositionAPI 在 Vue 3 中構建一個組件,該組件將值從 json 物件回傳到螢屏。到目前為止,我已經將組件設定為從本地 data.json 檔案中獲取值,然后將值回傳給模板。data.json 檔案包含具有多個值的單個物件。我希望使用 Math.round() 將每個值四舍五入到最接近的整數。為此,我創建了一個計算屬性,它對 data.json 中的資料進行四舍五入,如下所示:
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)
}
但是,這仍然不會對物件中的值進行四舍五入,每個值都有自己的名稱(val、val2、val3、val4)。如何使用 Math.round() 或 Math.toFix(2) 來對從 data.json 回傳的所有值進行舍入?
這是其余的代碼:
組件(帶有 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>
資料.json:
{
"val": 1.446565,
"val2": 45.678,
"val3": 56.75,
"val4": 78.98
}
uj5u.com熱心網友回復:
> const roundedValue = () => {
> const roundData = {}
> Object.keys(data.value).map(key => {
> return roundData[key] = Math.round(data.value[key]);
> })
>
> return roundData
> }
你可以試試這個。函式回傳舍入值
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463617.html
標籤:javascript json Vue.js 目的 数学圆
