
I want my component to accept different formula for computation of last column and use that formula to vuex getters to store the total of state that I passed in my component.
Component I want to make: -Can have dynamic columns ✓ -Can accept dynamic formula X -Specify what column to add in formula X
Below is the code of my component
<template>
<div>
<h2 class="text-center">{{ title }}</h2>
<v-row>
<v-col v-for="(header, i) in headers" :key="i">
<div class="text-center">{{ header.text }}</div>
</v-col>
</v-row>
<v-row class="align-center" v-for="(item, i) in stateArr" :key="i">
<v-col v-for="(header, j) in headers" :key="j">
<div v-if="header.type == 'number'" class="text-center">
{{ i + 1 }}
</div>
<div v-if="header.type == 'input'">
<v-text-field
outlined
dense
hide-details="auto"
:value="item[header.value]"
@input="commit(i, header.value, $event)"
>
</v-text-field>
</div>
</v-col>
</v-row>
<v-row>
<v-col>
<h2 class="text-center">Total</h2>
</v-col>
<v-spacer></v-spacer>
<v-col>
<h2 class="text-center">0</h2>
</v-col>
</v-row>
</div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
props: {
stateName: {
default: "",
},
headers: {
default: () => [],
},
title: {
default: "",
},
rows: {
default: 5,
},
},
mounted() {
for (let i = 0; i < this.rows; i++) {
this.addRow(this.stateName);
}
},
computed: {
...mapState({
stateArr(state) {
return state[this.stateName];
},
}),
},
methods: {
...mapMutations(["mutateArr", "addRow", "reduceRow"]),
commit(index, property, val) {
this.mutateArr({
name: this.stateName,
index: index,
property: property,
val: val,
});
},
},
};
</script>
You will have to write some formula parsing logic. Let suppose you want to implement a formula to sum values of X,Y columns and write that in Z column. Formula you would write in Z column would be something like X[1]+Y[1]. Now in JavaScript, its upto you how you parse it.
One way would be
getInput(formula) {
const arr = formula.split('+')
const isPositiveOperation = arr.length > 1
if(isPositiveOperation) {
const xIndex = arr[0].split('X[')[0].split(']')
const yIndex = arr[1].split('X[')[0].split(']')
const xValue = this.xItems[xIndex]
const yValue = this.yItems[yIndex]
return xValue + yValue
}
}
This is very basic of course. You can look into regular expressions for more robust solutions.