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

Working with high-resolution images on HTML5 canvas

I am faced with a challenge of incorporating a 15000x15000 px vector image as the backdrop for my canvas project. It is essential to crop specific sections of this image swiftly and consistently, especially within requestAnimationFrame. My current method ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

The continuous resizing of the window is triggering a loop in flexslider when the resize function is called

I am currently working on a website that utilizes the flexslider plugin. My goal is to detect when the browser window is resized, and then reinitialize the slider so that it can adjust its size and other parameters accordingly. Initially, I was able to a ...

Nuxt router directing to incorrect URL upon refreshing the page

Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...

How to align scrolling images with their scroll origin - a step by step guide

Curious to know the name of the effect where images scroll in a different orientation than the page, creating a 2D appearance. Take a look at the Google Nexus website and scroll down - do you see the effect? What is this effect called? Is it created usin ...

What is the best way to ensure type safety in a Promise using Typescript?

It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve function accepts undefined, while Promise.then infers the argument to be non-undefined: function f() { return new Promise<number>((resolve) ...

Troubleshooting a unique CSS bug in jQuery mouseover functionality

Check out this pen: https://codepen.io/anon/pen/eKzEVX?editors=1111 I recently created a Form Select in Laravel: {!! Form::select('status_id', $statuses, $post->status_id, ['class' => 'form-control post-sub-items-label &apo ...

Restricting the height of the grid list in Vuetify

Lately, I've been working with Vue.js and the Vuetify framework, and I encountered a challenge that has me stumped. In certain instances, I need to present data in a grid layout using the vuetify grid component. After examining the code, I decided t ...

Deploying a Vue and Express application on Heroku without utilizing the Single Page Application located in the server/public directory

I have deployed my application on Heroku, and the routes are returning JSON files. However, I want to serve the Single Page Application (SPA) located in my ./server/public folder as the index.html file. Whenever I access the Heroku app, it displays the JSO ...

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

Bootstrap carousel button that tracks the number of clicks

Unfortunately, I am facing a challenging issue with creating a click counter for the Bootstrap carousel button. The problem seems to be related to the span element for the previous and next icons. The button counter is not registering clicks on the respec ...

Adjust the color of the glyphicon icon within a date and time picker dropdown component

I decided to implement the bootstrap datetimepicker using this gem and utilized the following HTML code: <div id="custom-dates" style=" clear:both;"> <div class="container"> <div class="row"> <div class='col-md-3 col-xs-3' ...

Is it possible to load a JS file without using the require function?

Is there a method to load a JavaScript file without using require, but with fs for instance? I am aware that for JSON files I can utilize: const jsonFile = JSON.parse(fs.readFileSync("/jsonfile.json")) Can the same be done for a JavaScript file? I am inq ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

Retrieving values from multiple inputs in NightwatchJS

Can nightwatchjs be used to retrieve values from multiple inputs simultaneously? I am looking to verify the values of several input fields at once. Your help is much appreciated. ...

Jquery draggable droppable does not support displaying multiple divs simultaneously

I tried to implement the jquery ui draggable and droppable features to display 3 divs within a designated area. Below is the code snippet: --CSS: #content-1 { width: 200px; height: 100px; border: 1px solid red; display: none; } #content-2 { width: ...

looking to showcase the highest 'levelNumber' of elements within an array

arr1 = [ { "levelNumber": "2", "name": "abc", }, { "levelNumber": "3", "name": "abc" }, { "levelNumber": "3", "name": &quo ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

Utilizing JavaScript variable modifiers for enhanced functionality

I'm trying to find a way to perform a case-insensitive search for a variable within a string. To achieve this, I'm using the /gi modifier to ignore case sensitivity. However, the challenge arises because identifiers only accept direct strings rat ...

Generating an array of objects using Jquery from XML data

I need assistance with extracting data from XML text nodes stored in a variable and then creating an array of objects using jQuery. The XML data I have is as follows: var header = ['name', 'data1', 'data2']; var data = &apos ...