Utilizing child value to update parent value in VUE JS

I am looking to update the Total value in the parent component based on values from the child components.

<!--Parent Component-->
<template>
  <div class="section__wrapper">
      <h1>Total:{{ this.total }}</h1>
      <vItem title="First Item" price=2 @clicked="onClickChild"></vItem>
      <vItem title="Second Item" price=3  @clicked="onClickChild"></vItem>
  </div>
</template> 

<script>
import vItem from './v-item.vue';
export default {
   data(){
      return{
         total:1000000,
      }
   },
   components: {
      vItem
  }
}
</script>


<!--Child Component-->
<template>
  <div class="item__body">
   <div class="item__body__content">
      <img src="" alt="" class="item__body__content__img">
      <p>{{ this.totalOfItem }}</p>
      <p class="item__body__content__title">{{ this.title }}</p>
      <p class="item__body__content__price">{{ this.price }}</p>
      <div class="item__body__content__control">
         <button class="item__body__content__btn sell" @click="increasePrice">sell</button>
         <input type="text" class="item__body__content__input" :value=this.count>
         <button class="item__body__content__btn buy" @click="decreasePrice">buy</button>
      </div>
   </div>
  </div>
</template>

<script>

export default {
   props: {
    title: String,
    price: Number,

  },
  data(){
   return{
      count:0,
      totalOfItem: 0
   }
  },
  methods:{
   increasePrice(){
      this.count -= 1
      this.totalOfItem = this.count * this.price
   },
   decreasePrice(){
      this.count += 1
      this.totalOfItem = this.count * this.price
   },

  }
}
</script>

I need a method that decreases the total based on the number of different products. While it's simple for a single product, it becomes more complex with multiple products. Each item has its own price and quantity.

Answer №1

Check out the Vue.js documentation on how to use emits: https://vuejs.org/guide/components/events.html.

Here's an example of how you can implement it in your child component:

export default {
   props: {
    title: String,
    price: Number,
  },
  data(){
   return{
      count:0,
      totalOfItem: 0
   }
  },
  emits: ['onClickChild'],
  setup(props, emit) {
   function increasePrice(){
      this.count -= 1
      this.totalOfItem = this.count * this.price
      emit('onClickChild', this.totalOfItem)
   }

   function decreasePrice(){
      this.count += 1
      this.totalOfItem = this.count * this.price
      emit('onClickChild', this.totalOfItem)
   }
   
   return {
      increasePrice,
      decreasePrice,
   }
  }
}

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

Retrieving the dynamically selected table row ID using Javascript

Within my application, I am dynamically adding new rows with unique IDs assigned from a loop. When creating a Purchase Order in the view, I am adding these rows to a table. Now, when the value of Select changes, I need to capture the changed row ID and t ...

Is it possible to apply CSS styling to a flex-item once it wraps onto a different row?

.wrapper { border: 5px solid pink; display: flex; flex-wrap: wrap; justify-content: center; } .a-fc { background-color: purple; width: 300px; /*height: 100px;*/ } .b-fc { background-color: orange; display: flex; flex-direction: ...

Video background mute feature malfunctioning

I've searched through numerous resources and reviewed various solutions for this issue, yet I still haven't been able to figure it out. Could someone please guide me on how to mute my youtube embedded video? P.s. I am a beginner when it comes to ...

What is the best way to ensure a string of words in HTML/CSS wraps to the next line seamlessly?

As I work on creating my portfolio website using Bootstrap and custom CSS, I am running into an issue with the game titles breaking in the middle when displayed. Despite my limited proficiency in English, I tried searching for a solution without success. ...

Is it possible to return an array of middleware from one middleware to another in Express JS?

Looking to display shop information through a route. The route setup is as follows: router.param('userId',getUserById) router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail) My goal is to send different responses based ...

Problem encountered with Blueimp gallery and Twitter Bootstrap

Blueimp gallery is being used to showcase a set of 8 images on a website, divided into two rows. The 5th thumbnail (first image on the second row) appears broken, even though it can be seen in the carousel presentation. Here's the link to view the th ...

Issue encountered with v-for in Vue.js

Rendering a table dynamically based on ajax requests has been my goal. The Backend is all set up correctly, and the data from the response package gets loaded successfully into my variables when I run the code. However, a stumbling block occurs when I vie ...

Can someone explain what logForm.$invalid.$setValidity is all about?

The code snippet can be found here I am a beginner in this field and currently studying a piece of code. I am having trouble understanding the logForm.$invalid.$setValidity line. I have searched online but couldn't find any information about it. The ...

Run a PHP statement when a JavaScript condition evaluates to true

I am attempting to run a php statement if my javascript condition is true. Here is the code snippet that I have written: <input id="checkbox1" type="checkbox"> MSI<br></input> <script> $(document).ready(function(){ $(&apos ...

Receive information on browser activity

Is there a way to trigger an event when the following actions occur: Pressing the reload icon in the browser Pressing the Back or Forward icon in the browser Selecting the Reload menu item from the browser context menu Selecting the Reload option from t ...

If there are multiple Monaco diff editors present on a single page, only the first instance will display the diff

I'm currently working with a Vue component that renders a diff editor using Monaco. However, when I have more than one instance of this component on the same page, only the first one displays the diff highlights. Here is the template: <template> ...

Mastering the implementation of owl-carousel in React.js

I'm currently working on a project that involves utilizing the react framework. My intention is to incorporate the owl-carousel, however, I've encountered issues as it fails to function properly. The following error keeps popping up: OwlCarousel ...

Tips for clearing object values without deleting the keys: Resetting the values of an object and its

Upon creating a service to share data among multiple components, it became necessary to reset the object values once the process was complete. To achieve this, I attempted the following: this.UserDetails = {}; This successfully cleared the values and remov ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

Ways to update the canvas every x seconds

Is there a way to automatically update my canvas every x seconds without having to reload the entire page? <script> $(document).ready(function () { var odo = new RGraph.Odometer({ id: 'cvs', min: 0, max: 360, ...

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

Error message: 'import not located' when using custom types in Vue 3 with Vite/Vitesse

I'm currently working on a Vue 3 project using Vitesse (which is based on Vite). I created a custom type called ProductData in my src/types.ts file. However, when I try to use this type in one of my pages, the page fails to load and I see multiple con ...

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

Tips for supplying environmental variables from an external source to a React application

. ├── backend │ ├── node_modules │ ├── package.json │ ├── routes │ └── server.js ├── frontend │ ├── node_modules │ ├── package.json │ ├── public │ └── src ├── ...

Tips for ensuring only one submenu is open at a time

I have successfully created a responsive menu that is working well. However, I am facing an issue. I want only one menu to be open at a time. When a submenu is opened, the other menus should be hidden. How can I achieve this? Below is my Script code $( ...