Using Vue.js, perform calculations on various fields within an array of objects generated by the v-for directive

I am currently learning Vue.js and I have implemented a v-for loop to iterate through an array of objects. However, I now need to calculate a specific field (precoPorKg) within this loop.

In order to perform this calculation, the input item.quantidade must contain a value. Once that is done, I will use the following formula:

(item.quantidade * item.valorUnitario)/( item.quantidade * item.pesoUnitario)

This is how my v-for looks:

<tr v-for="(item, index) in step2">
    <td>{{ item.produto }}</td>
   <td><input type="text" v-model="item.quantidade"></td>
    <td>{{ item.valorUnitario }}</td>
    <td>{{ item.pesoUnitario }}</td>
    <td>{{ item.cubagemUnitaria }}</td>
    <td>{{ calcPrecoPorKg(index, item) }}</td> 
</tr>

Here is my Vue component (I've attempted to handle the operation within 'computed', but it's not working as intended):

new Vue({
    el: '#app', 
    data(){
        step2 : [
          {
            produto: 'A70-5',
            descricao: 'basketball',
            ncm: '950.6',
            quantidade: '',
            valorUnitario: '0.78',
           pesoUnitario: '0.430',
            cubagemUnitaria: '0.00',
            precoPorKg: '',
          }
     ],
 computed: {
    calcPrecoPorKg: function (index, item) {
        return (item.quantidade * item.valorUnitario)/( item.quantidade * item.pesoUnitario);
              }
         }

})

Answer №1

When dealing with computed properties, it's important to remember that they do not accept any parameters. In this case, a method is what you actually need.

methods: {
  calculatePricePerKg(item) {
    return (item.quantity * item.unitPrice)/(item.quantity * item.weight);
  }
}

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

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Try making a series of interconnected fetch requests in Redux Toolkit that rely on the completion of the previous fetch

I am still learning the ropes of Redux and I'm feeling a bit lost. My goal is to make two API calls - one to retrieve an account Id and a category Id, and another to get a list of transactions based on those IDs. The createApi function in my code lo ...

InvalidAction: The function forEach cannot be applied to "res"

Here is the HTML code that I am currently working with: <div *ngIf="chart" class="col-xl-4 col-lg-6"> <div class="card cardColor mb-3"> <div class="card-header headColor"> <img class="img-fluid" src="../../../ ...

Managing numerous ajax forms within a single page

Upon receiving advice from the following inquiry Multiple forms in a page - loading error messages via ajax, I am endeavoring to incorporate multiple forms within one page. The goal is to insert error messages into the corresponding input div classes. I pr ...

Ways to prevent the Layout component from rendering on the NextJS login page

Is there a way to prevent the rendering of the Layout component in NextJS when the route is /login, /register, etc? const MyApp = ({ Component, pageProps }) => { return ( <Layout> <Component {...pageProps} /> </Layout> ...

Store the running of a JavaScript file in memory

It seems highly unlikely that achieving the following is possible without expert confirmation: On page number 1, user and application data is requested as soon as the page loads. Page number 2 utilizes the same script, so requesting the same information w ...

Alignment issue with Ul dropdown menus and shadow

After stumbling upon a fascinating menu design at this link, I decided to tweak it for center alignment by following the advice on this forum thread. Unfortunately, my efforts have hit a roadblock - the drop down menus aren't aligning as intended and ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Combining vue.js and gulp to simplify development and create a unified js and css file

Looking for help with merging app.js and bundle.js together in my gulpfile.js. Also need to merge app.css and bundle.css. How can I start the "scripts" and "styles" tasks after running the "vue" task? Is it better to use webpack instead of gulp? ...

What is the best method for storing a Google Analytics object in a $_SESSION variable when transitioning between PHP scripts to avoid encountering a non-object error

Currently in the process of developing a web application that integrates with the Google Analytics API, however encountering challenges when it comes to implementation. The user is given the option to choose their profile from three interconnected drop-do ...

Set Divs in Absolute Position Relative to Each Other

I need to create a simple navigation system using <div> elements as individual pages. The goal is to have "next" and "back" buttons that allow users to switch between these pages with a smooth fade-in and fade-out effect, all powered by jQuery. Howev ...

Experiencing challenges during the creation of a NUXT build

Trying to build a Nuxt SSR app, but encountering an error related to the css-loader during the build command execution. The issue seems to be with Invalid options object. ERROR in ./node_modules/vue2-google-maps/dist/components/streetViewPanorama.vue (./no ...

What is the ideal destination for my Ajax request to be sent?

When utilizing jQuery, in the event of sending an Ajax request you must provide the URL to direct towards. For instance: $.get("someurl", function(data) { console.log(data); }); The query at hand is: should the URL indicate a page on the server, trea ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

"We are experiencing issues with the app.get function and it is

Although my backend is successfully serving other files, I have encountered an issue with loading new files that are located in a folder named js within the directory. These specific files are not being loaded, and despite spending an hour trying to troubl ...

javascript does not function properly within the UI router view

In my latest project, I have used a combination of Node.js, AngularJS, and HTML. The main HTML file is named "main.html". <html> <head> <script src="angularJs.js"></script> <script src="ui-router.js">< ...

Tips for serving a minified JavaScript file located in the dist directory on GitHub Pages

I recently followed a tutorial on creating an app using VueJS cli and now I want to deploy it on gh-pages. After generating the dist folder with the yarn generate command, I referred to a deployment guide to publish the app. However, when I visit the dep ...

updating container with wire:ignore in laravel livewire

Incorporating a Vue component into a Livewire component, specifically using a DatePicker component: <div id="customDiv" class="col-12 col-md-6 m-1" wire:ignore> <date-picker v-model="date" ...

An object will not be returned unless the opening curly bracket is positioned directly next to the return statement

compClasses: function() { /* The functionality is different depending on the placement of curly brackets */ return { major: this.valA, minor: this.valB } /* It works like this, please pay attention to ...