Is there a way to create a Vue component that can process dynamic formulas similar to those used in

I am looking to create a component that has the ability to accept different formulas for computing the last column. The component should use these formulas in Vuex getters to store the total state values passed to it.

Here are the specifications for the component I want to build: - Dynamic columns support ✓ - Ability to accept dynamic formulas X - Option to specify which columns to include in the formula X

Below you can find the code snippet of the 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>

Answer №1

In order to implement a formula for summing values from columns X and Y, you will need to create formula parsing logic. For example, if you want to write a formula in column Z that adds the values of X[1] and Y[1], you would need to parse it using JavaScript.

One approach could be as follows:

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 a simple example, and there are more advanced solutions using regular expressions for parsing formulas.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to sorting in JavaScript?

I need help with sorting an array. The array I have looks like this: var temp = [{"rank":3,"name":"Xan"},{"rank":1,"name":"Man"},{"rank":2,"name":"Han"}] I've tried to sort it using the following code: temp.sort(function(a){ a.rank}) But unfortun ...

Chrome now supports clickable circular canvas corners

I have a unique setup with two canvases. I've customized them to be circular by utilizing the border-radius property. The second canvas is positioned perfectly within the boundaries of the first one using absolute positioning. This is where it gets e ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

Get all the classes from the body element of the AJAX-loaded page and update the body classes on the current page with them

I am currently in the process of AJAX-ing a WordPress theme with a persistent music player. In Wordpress, dynamic classes are used on the <body> tag. The structure I'm working with looks like this: <html> <head> </head> ...

I am looking to insert an array of a specific type into a Postgres database using Node.js, but I am unsure of the process

query.callfunction('fn_create_mp_product', parameters, (err, result) => { if (err) { console.log(err) callback(err); } else { if (result.status == 'success') { callb ...

What is the method for ensuring text remains within a square while it is being relocated?

Check out this jsfiddle where you can interact with a moving square: http://jsfiddle.net/helpme128/3kwwo53t/2/ <div ng-app="test" ng-controller="testCtrl"> <div id="container"> <div class="shape" ng-draggable='dragOptions& ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Load/run JavaScript code before sending email blade template

Is it feasible to embed and run JavaScript code in a blade template before sending an email? The challenge lies in sending users some dynamically generated images from a third-party program requested via AJAX. The current setup is as follows: //report. ...

Nuxt2 is not compatible with the current Long-Term Support version of Node (v18)

As a newcomer, I am embarking on my first Vue.js project with Nuxt. After executing "npm run dev" in the command prompt and running "npm install" for my project, I encountered the following: * Client ██████████████████ ...

Ways to retrieve output from a JavaScript function

How can I successfully return the result from response.on within the signIn function? const signIn = async (password) => { var request = new DeviceAuthQuery(); request.setPassword(password); var response = client.authenticate(request, {}, (err, ...

How can I display only the y-axis values and hide the default y-axis line in react-chartjs-2?

Although I have some experience with chartjs, I am struggling to figure out how to hide the default line. To clarify, I have attached an image that illustrates the issue. I would like to achieve a result similar to this example: . My goal is to make it loo ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

Hide a single column in a Vue b-table

As a newcomer to Vue, I am using Vue and Bootstrap-vue to paginate my data from nameList in this project. Is there a way I can hide the column nameList.id and only display the first_name and last_name? Check out the code on JsFiddle = https://jsfiddle.net ...

How can I utilize jQuery to iterate through every anchor tag on an HTML page?

I am looking to reference all anchor tags on the page that have a parent h2 tag. To achieve this, I need to iterate through each anchor tag that has a parent h2 and add an attribute using jQuery. <body> <h1>not me</h1> <a href ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for this in Chart.js? Thanks! ...

What is the reason for encountering an error when attempting to use a let variable in a new block before reassigning it

Check out this document here where I attempt to explain a coding scenario: // declare variables const x = 1; let y = 2; var z = 3; console.log(`Global scope - x, y, z: ${x}, ${y}, ${z}`); if (true) { console.log(`A new block scope - x, y, z: ${x}, $ ...

storing information between elements

Imagine I have a requirement to include a data provider element for my users, like this: <user-data-provider user-data="{{data}}"></user-data-provider> This element would send an ajax request to retrieve the logged in user's information. ...

Tips for setting up npm dependencies in a subfolder

Within the main directory, I have a package.json file that contains this command: "install": "cd packages/my-package && yarn". Every time I execute yarn run install, my intention is for it to enter into the specified package, set up the node modul ...