1๐
โ
I created a below code snippet as per your requirement. Please find the explanation of the logic inline in the snippet.
const app = new Vue({
el: '#app',
data() {
return {
guild_size_inch: [
{
size: "S",
chest: "92",
length: "71"
},
{
size: "M",
chest: "40",
length: "29"
},
{
size: "L",
chest: "44",
length: "30"
}
],
isInch: true, // property to enable/disable the 'Inch' button.
isCM: false // property to enable/disable the 'CM' button.
}
},
methods: {
// Method used to convert the Inch values into CM.
changeToCM() {
this.isCM = true;
this.isInch = false;
this.guild_size_inch = this.guild_size_inch.map((obj) => {
obj.chest = parseInt(obj.chest) * 2.54;
obj.length = parseInt(obj.length) * 2.54;
return obj;
});
},
// Method used to convert the CM values into Inch.
changeToInch() {
this.isCM = false;
this.isInch = true;
this.guild_size_inch = this.guild_size_inch.map((obj) => {
obj.chest = Math.ceil(parseInt(obj.chest) / 2.54);
obj.length = Math.ceil(parseInt(obj.length) / 2.54);
return obj;
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="changeToInch" :disabled="isInch">Inch (Default)</button>
<button @click="changeToCM" :disabled="isCM">CM</button>
<table>
<th>Size</th>
<th>Chest</th>
<th>Length</th>
<tr v-for="(item, index) in guild_size_inch" :key="index">
<td>{{ item.size }}</td>
<td>{{ item.chest }}</td>
<td>{{ item.length }}</td>
</tr>
</table>
</div>
๐คDebug Diva
1๐
You are trying to multiply the object instead of the numbers contains in your object.
What you should try is loop through your array and multiply both chest and length.
You can perform this with a forEach
loop : see documentation here
changeToCM: function() {
this.guild_size_inch.forEach(item => {
item.chest = parseInt(item.chest) * 2.54
item.length = parseInt(item.length) * 2.54
});
alert(this.guild_size_inch)
}
๐คRenaudC5
1๐
Define a property called currentUnit
initially set to inch
which will be changes by the click event, then use a computed property that returns the sizes based on the current unit which you selected :
data() {
return {
guild_size_inch:[....],
currentUnit:'cm'
}
},
computed:{
sizes(){
return this.guild_size_inch.map(size=>{
size.chest=this.currentUnit==='cm'?size.chest*2.54:size.chest*2.54
size.length=this.currentUnit==='cm'?size.length/2.54:size.length/2.54
return size;
})
}
},
methods:{
changeUnit() {
this.currentUnit==='cm'?this.currentUnit='inch':this.currentUnit='cm'
}
}
then render the sizes
in the table.
Source:stackexchange.com