繁体   English   中英

我可以让我的 Vue 组件接受像 excel 这样的动态公式吗?

[英]Can I make my Vue component accept dynamic formula like excel?

我的组件

我希望我的组件接受不同的公式来计算最后一列,并将该公式用于 vuex getter 以存储我在组件中传递的 state 的总数。

我要制作的组件: - 可以有动态列 ✓ - 可以接受动态公式 X - 指定要在公式 X 中添加的列

下面是我的组件的代码

<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>

您将不得不编写一些公式解析逻辑。 假设您要实现一个公式来对 X、Y 列的值求和并将其写入 Z 列。 您将在 Z 列中编写的公式类似于 X[1]+Y[1]。 现在在 JavaScript 中,由您决定如何解析它。

一种方法是

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
 }
}

这当然是非常基本的。 您可以查看正则表达式以获得更强大的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM