Dynamic shopping cart with Vue.js

Currently, I am working on a shopping cart project using Vue.js and Vuetify.

I need help figuring out how to capture the boolean value true or false and adjust the total price in the amount based on whether it is true or false. Any suggestions?

<v-container grid-list-md text-xs-center>
        <v-card class="">
            <h2 class="headline mb-0">Extra ingredients:</h2>
            <v-layout row wrap class="text-xs-center" v-for="ingredient in ingredients" :key="ingredient.id">
                <v-layout column>
                    <v-flex xs6>
                        <v-checkbox name="checkbox" color="light-blue lighten-2" v-bind:label="`${ingredient.name}`" v-model="ingredient.checked" light></v-checkbox>
                    </v-flex>
                </v-layout>
                <v-layout column>
                    <v-flex xs6>
                        <v-subheader>{{ingredient.price}} €</v-subheader>
                    </v-flex>
                </v-layout>
            </v-layout>
            <v-divider></v-divider>
            <v-layout row wrap class="mb-3">
                <v-flex xs6>
                    <h3 class="headline mb-0">Total price:</h3>
                </v-flex>
            </v-layout>
    </v-card>
    </v-layout>

    <script>

    export default {
        data: () => ({

            checked1: '',
            ingredients: [{
                id: 1,
                name: "cheese",
                price: 2,
                checked: '',
            }, {
                id: 2,
                name: "ham",
                price: 2.0,
                checked: '',
            }, {
                id: 3,
                name: "Bacon",
                price: 2.25,
                checked: '',
            }, {
                id: 4,
                name: "spinac",
                price: 1.6,
                checked: '',
            }, {
                id: 5,
                name: "extracheese",
                price: 2.5,
                checked: '',
            }, {
                id: 6,
                name: "pepper",
                price: 2.75,
                checked: '',
            }],

        }),
        computed: {

            total() {
                var total = 0;
                for (var i = 0; i < this.ingredients.length; i++) {

                    total += this.ingredients[i].price;
                }
                return total;
            }
        },
        methods: {
          addToCart(item){
            amount = 0;
            if(ingredient.checked == true){
              amount += ingredient.price;
            }
            else {
              amount -= ingredient.price;
            }
          }
        }

    }

    </script>

Answer №1

The boolean value you are looking for is stored in ingredient.checked, which can be utilized to control the display of the price using either v-if or v-show:

<v-subheader v-if="ingredient.checked">{{ingredient.price}} €</v-subheader>

To calculate the total value (assuming you only want to add the price of checked items), a small change is required:

   computed: {
        total() {
            var total = 0;
            for (var i = 0; i < this.ingredients.length; i++) {
                if (this.ingredients[i].checked) { // <-- update here
                    total += this.ingredients[i].price;
                }
            }
            return total;
        }
    },

You can then display the computed value just like any other variable:

<h3 class="headline mb-0">Total price: {{total}}</h3>

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

"Can you provide instructions on placing a span within an image

I am trying to figure out how to insert a <span> into an <image>, similar to the effect on the page . However, I do not want this effect to occur on hover(), but rather on click(). My goal is to insert "data-title" into the <span> and hav ...

Mongoose schema nesting guide

I've encountered an issue while attempting to nest schemas in mongoose, and unfortunately I'm struggling to pinpoint the exact cause. Here's what my current setup looks like. Starting with the parent schema: const Comment = require("./Comm ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

Combining the power of Angular.js and Require.js

As I develop a local app on nw.js using angular.js, I'm starting to question my approach. In my controller, I often find myself writing code like this: .controller('UserSettingsCtrl', function($scope, $mdDialog, $translate) { var fs = ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

Utilizing a class instance as a static property - a step-by-step guide

In my code, I am trying to establish a static property for a class called OuterClass. This static property should hold an instance of another class named InnerClass. The InnerClass definition consists of a property and a function as shown below: // InnerC ...

What is the best way to send a parameter to a Javascript .done callback from a .success method?

Is there a way to transfer information from a .success function to a done function? $.ajax({ url: "/Asgard/SetLanguagesElf", success: function () { var amount = 7; }, error: function () { alert("SetLanguagesElf"); }, type: &apo ...

The Minimax algorithm experiencing issues in Next.js

I recently wrote some code in Next.js, but unfortunately, it's not functioning as expected. Despite my best efforts and attempts at utilizing alpha beta pruning, the code still fails to work properly. The issue lies in the fact that it simply returns ...

Deleting data from Firebase in Angular can be easily done using the AngularFire library. By

I am attempting to remove specific values from my Firebase database. I need to delete this entry from Firebase: https://i.stack.imgur.com/CAUHX.png So far, I have tried using a button to trigger the delete function like this: <div class="single-bfunc ...

There was a dependency resolution error encountered when resolving the following: [email protected] 12:15:56 AM: npm ERR! Discovered: [email protected] . The Netlify deploy log is provided below for reference

5:27:42 PM: Installing npm packages using npm version 8.19.3 5:27:44 PM: npm ERR! code ERESOLVE 5:27:44 PM: npm ERR! ERESOLVE could not resolve 5:27:44 PM: npm ERR! 5:27:44 PM: npm ERR! While resolving: [email protected] 5:27:44 PM: npm ERR! Foun ...

Combine array in MongoDB containing nested documents

I need assistance with querying my MongoDB database: Specifically, I want to retrieve data that is nested within an array and filter it based on a specific key within the nested structure. The example document looks like this: [ { "name": ...

Can webpack integrate React components from a package and then recompile the package?

I am currently in the process of creating an npm package to standardize my layout components that are based on geist components. Initially, I attempted to use the npm package as a local component, but encountered a webpack loader error when trying to read ...

Should I reload the entire table or insert a row manually?

This unique ajax question arises: within a table lies the users' information, displayed based on individual settings and timing. Sometimes, users instantly see the data, other times they must wait for it - their choice determines when it appears. Wha ...

You are required to select one of the two radio buttons in order to proceed with the validation process

To prevent the user from proceeding to the next page, validation is necessary. They are required to select one of the radio buttons, etc. <div class=""> <div class="radiho" style="display: block"> <input type="checkbox" name="sp ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

Tips for designing a personalized payment page in PayPal for flexible one-time and subscription-based payments

How can I display a PayPal checkout page with custom fields such as tax and total amount when a user makes a payment for a custom amount? Can multiple fields like sales tax and total amount be added? In addition to that, our web application already has Pa ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Display the date that is 3 days after the selected date from the Date Picker in the text field

This is the date picker code I am currently using: var d = new Date(); $(function () { $("#datepicker").datepicker({ minDate: d, dateFormat: 'mm-dd-yy' }); }); I want to enhance this functionality so that when a date is ...

Unveil as you scroll - ScrollMagic

I am working on a skill chart that dynamically fills when the document loads. I am exploring the possibility of using ScrollMagic to animate the chart filling as the user scrolls down. After trying various combinations of classes and pseudo-classes in the ...