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

Incorporating library files (css/js) into your app built on the angular-fullstack framework

After using a Yo Angular-Fullstack generator (https://github.com/DaftMonk/generator-angular-fullstack) to start an app, I attempted to install Toastr from bower with the command: bower install angular-toastr Now, I need to add the toastr css and js files ...

Invoke the wrapper function within the jQuery AJAX `complete` callback

I am currently trying to accomplish a task, but I keep receiving an error message stating that I cannot bind to undefined. I suspect this is happening because I am working within an anonymous function. My goal is to be able to access the method (getAndSayH ...

Creating a customizable file upload component in Vue.js: A step-by-step guide

In my current project, I am faced with the task of implementing an upload file component in various styles. My goal is to create a highly customizable component that allows for easy design modifications without repeating code and consolidating common logic ...

To show the image along with the .titleclass, .subtitleclass, and .description when clicking on it, what steps do I

<?php while($galleryrec = mysqli_fetch_array($getresultgallery)){ ?> <div class="col-lg-2 col-md-2 mb-4 mb-lg-0" id="imageidback"> <img data-id ="<?php echo $galleryrec['publishid& ...

Is there a way to streamline this generator without using recursion?

I need to develop a unique value generator that produces values within a specified range. The criteria are: all generated values must be distinct the order of values remains consistent upon each run of the generator each value should be significantly diff ...

Express is throwing an error indicating that the specified route cannot be found. Is there a way to dynamically

After dynamically adding routes and sending a post request through Postman, I encountered a "not found" error message. In the app, a 404 is logged next to the endpoint, indicating that Express cannot locate it. However, I know that I added the router dynam ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

Sliding Image Menu using jQuery

I am struggling with creating a menu using jquery mouseenter / mouseout effects. My goal is to have a small icon displayed that expands to the left and reveals the menu link when a user hovers over it. The issue I am facing is that the effect only works w ...

#Error 500 encountered in a basic Ruby on Rails and AngularJS collaboration

Thanks to everyone for taking the time to assist me with this problem. As a newcomer to Ruby, the solution may be quite simple. I have developed an API that facilitates communication between Ruby and Angularjs. Here is the API: class EntriesController < ...

PhantomJS encountered a TypeError when trying to access a non-existent object during the evaluation of 'document.getElementById()'

Recently, I delved into the world of PhantomJS and its ability to extract data from websites through JavaScript. This process is commonly referred to as web scraping. My goal was to retrieve the text content of an element by its ID. However, I encountered ...

Troubleshooting issues with applying styles in Vue framework when configured with webpack

I'm facing an issue with setting up the Vue framework using webpack. Specifically, I'm having trouble with styles not being applied when included in the <style> tag within single file components. Despite following several tutorials on this ...

Ways to retrieve the worldwide status across multiple Vue.js components

I am looking to create multiple characters in separate components. My question revolves around efficiently accessing a global variable without redundancy in code. I currently have an array containing 10 characters. index.js state: { ...

Is there a way to retrieve nested data from a JSON API response?

Trying my hand at creating a basic CLI cryptocurrency tracker app. The app runs a successful API call and provides the following output: [ { exchange: 'binance', base: 'ADA', quote: 'BTC', price_quote: '0.000 ...

How can you enhance the visibility of AngularJS Materials dropdown menus?

While experimenting with AngularJS Materials, I noticed that the text in some elements like <md-input-container> and <md-select> may be too light for some people to read easily. I wanted to find a way to make the text more visible without chang ...

What are the methods for providing both successful and unsuccessful promises, with or without data?

Seeking guidance on how to return a promise and an object named output before or after the $http call in AngularJS, specifically using Typescript. How can I ensure it works correctly? topicNewSubmit = (): ng.IPromise<any> => { var self = t ...

Using AngularJs to have two ui-views on a single page

As a beginner in AngularJs, I encountered an issue with having two ui-views on the same page. When I click a button to show the view for goals, both the form for goals appear in ui-view 1 and ui-view 2 simultaneously. I have been working with states but I ...

What is the best way to dynamically assign an id to an ajax Actionlink in ASP.NET?

I have a collection of items and each item contains an Ajax.ActionLink. I would like to dynamically set the id for each action link based on the item's id. @Ajax.ActionLink("Join","ajaxview", new{id = tour.TourId}, new { HttpMethod = "GET", Insertion ...

When you try to import a component, it may result in a blank page displaying an error message stating: "TypeError: Cannot set property 'components'

One interesting feature is the Vue component named DisplayContent, <template> <div></div> </template> <script lang="ts"> import { Vue, Component } from "vue-property-decorator"; import Home from "@/ ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...