Vue.js reactive total shopping cart

Can the total amount in the shopping basket be updated dynamically? For example, if I have two items in my cart that cost €18 and I add another item, I want the total to automatically adjust without needing to refresh the page. Currently, my 'calculate total' property gives me two separate options: 14.00 and 12.00. I would like it to calculate the sum dynamically as 14.00 + 12.00 = 26

Thank you for any assistance.

<template>
    <div>
      <div >
        
          <div >
            <u>
                <li v-for="item in shop" :key="item.id">
                    {{ item.label}} : {{ item.cost }}€
                </li>
            </u>
            <button @click="addItem">Add</button>
        </div>
       
        <div >
            <u>
                <li v-for="item in shop" :key="item.id">
                    {{ item.label}} : {{ item.cost }}€
                </li>
            </u>
            
        </div>
            <p>{{ total}}</p>
        </div>
    </div>
</template>

<script>
  computed:{
      totalbasket(){
            let total = 0
             this.shop.forEach(item=>{
                total += item.cost
                
            })
             
            return total
        }
}
</script>

Answer №1

It seems like the issue lies with the item.cost being stored as a string instead of a float. Converting the cost to floats before summing them up could potentially resolve the problem:

 calculateTotal(){
   let total = 0
   this.cartItems.forEach(item=>{
     total += parseFloat(item.cost)
   })
   return total
   }

Additionally, you currently have {{total}} in your template. It may be more appropriate to change this to {{totalCartAmount}}.

As highlighted by tony19, the JavaScript parseFloat function does not consider commas as decimal points. There is a discussion on how to address this issue here.

Answer №2

If you want to enhance the functionality of your items, consider adding an Add Button for each one and then utilizing the addItem(item) method. Here's an example implementation:

...
<li v-for="item in shop" :key="item.id">
  {{ item.label}} : {{ item.cost }}€
  <button @click="addItem(item)">Add</button>
</li>

With this set up, the addItem method will insert the item into the cart triggering the totalbasket event:

methods: {
  addItem(item) {
    this.shop.push(item)
  },
...
}

When displaying the final price, make sure to use totalbasket instead of total in your template:

<p>{{ totalbasket }}</p>

This should provide the desired functionality.

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

Monitor changes in Angular Reactive forms to retrieve the field name, as well as the previous value and the current value of the field

this.formData = this.fb.group({ field1: '', field2: '' }); this.formData.valueChanges.pipe(startWith(null), pairwise()) .subscribe(([previous, current]: [any, any]) => { console.log('PREVIOUS', previous); co ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

What is the method for incorporating a global function with a plugin to display notifications in Vue.js?

Recently, I encountered an issue while trying to create a global function using a plugin. Everything seemed to be working fine until I faced difficulties in displaying my notifications. Tired of repeating the notification display methods everywhere in my c ...

Encountering the 'navigator is not defined' error when attempting to generate a Next JS build

After developing a custom hook in Next JS to retrieve network online status using the JavaScript navigator.onLine property, everything seemed to work flawlessly on my local machine. However, upon running npm run build to compile the project, I encountered ...

Creating foreign key relationships using Entity Framework in a .NET 5.0 Web API

Building a net 5.0 web API backend with Vue frontend and SQL database. In my project, I am looking to establish a foreign key relationship in the "Zamestnanci" table where the attribute "Pozicia" should reference another table called "Pozicie". public cla ...

The Angular routing feature seems to be malfunctioning

I have encountered a frustrating issue with AngularJS routing and despite countless searches for solutions, I am still facing the same problem. In my root folder at c:\intepub\wwwroot\angular\, I have three files that I am testing under ...

Exploring A-Frame VR: Understanding the Distinction between Cursor and Raycaster

I'm in the process of developing a WebVR project that allows users to interact with the environment by 'clicking' on entities. Can you explain the distinction between using the cursor fuse attribute and the raycaster for interaction? ...

Surprising issues arise when converting a string to a datetime using Moment.js within Node.js

I am looking to convert the string '03/08/2017 01:00:01 ' into a datetime object in node.js in order to extract the specific day and month from the date. For example, for the given date, the month is 08 and the day is 03. Take a look at the foll ...

Utilizing Data From External Sources in a React Application

I have encountered an issue with displaying data from another page in a reusable table I created using React. Specifically, I am having trouble getting the value to be shown in <TableCell> Please check out this code sandbox link for reference ACCES ...

PHP and MySQL combination for efficient removal of multiple dropdown choices

I'm struggling to figure this out. Essentially, it's a form with multiple dropdown menus where users can select one or more items to filter MySQL data results. I want to dynamically update the other dropdown menus as the user makes selections. Fo ...

Bring in a particular module from the natural library (webpack)

I have been utilizing the npm natural library for tokenization, specifically in one line of code: let token = natural.StemmerJa.prototype.tokenizeAndStem(searchWord, true); My concern lies in how to properly import it in webpack, given that tokenizeAndSte ...

Could you provide a demonstration of using the React Widget's DateTimePicker for me?

Struggling to navigate through the murky waters of this date time picker library. The instructions seem more like obstacles than aids. I'm attempting to integrate this library into my project: After downloading Node.js and NPM on my Max, I executed ...

Transforming the CanvasRenderer into a WebGLRenderer

I'm interested in implementing a visual effect similar to the one demonstrated in the example here: To achieve this, I want to modify the renderer to use WebGLRenderer instead of CanvasRenderer by changing: renderer = new THREE.CanvasRenderer(); to ...

Having trouble with the if/else statement in JavaScript? Check out the Odin Project's Rock, Paper, Scissors tutorial

I have been working on solving the Rock, Paper, and Scissors project, but I am struggling with constructing the if/else statement. Despite multiple attempts, I still can't seem to get the correct output when running the program. For instance, when I ...

Encountered a problem when attempting to upload images to Cloudinary through the front-end and save the information in a MySQL database using Axios on Node JS

I am currently working on a web application using React. I have implemented a form where users can input text data and upload multiple image files. The goal is to store the submitted images on Cloudinary along with other text data in a MySQL database. Unf ...

Highlighting Text in VueJS event

I am currently working with a data table that has clickable rows. Everything is functioning properly, but I have run into an issue. When I try to highlight text within the row, it triggers the click event. I attempted to use the .exact modifier in hopes of ...

Including items into an array through user input

My goal is to create a form that allows users to choose from two different "activities". The information entered will be saved along with personal details, and later displayed below each corresponding activity. Additionally, I want to give the ability to a ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

Enable the automatic resizing of a div element

This div features inside: <div class="PF"> <img src="img" class="FollowerPic"> <span>Name</span> <div class="Text"></div> <div class="readURL"> ...

Is it feasible to manipulate MySQL data with a React Native application?

I'm considering developing a React Native mobile app that can interact with a remote MySQL database (stored in the cloud and not on the device) without utilizing PHP for the backend. Is this feasible? ...