Tips on how to change a child component's attribute using props in Vue.js?

I have a situation where I have an addToCart component within a foodList component. Additionally, there is another component called Cart. My goal is to reset the addToCart component's counter value to 0 whenever the cart is emptied.

App.vue

data() {
  return {
    msg: "Welcome to Your Food Ordering App",
    foodData:[],
    cart:[],
    reset:false
 };
},
methods: {
  emptyCart:function(){
    this.reset = true;
    this.cart = [];
  }
}

foodList.vue

export default {
  props:['foods','reset'],
  data() {
    return {

    };
  }
}

<addToCart :reset="reset"></addToCart>

addToCart

export default {
  props:['food','reset'],
  data(){
    return {
      counter:0
    }
  },
  beforeMount() {
    if(this.reset) {
      this.counter = 0;
    }
  }

In App.vue, I toggle the reset property to "true" and then pass it to foodList.vue, which in turn passes it to addToCart.vue.

Within addToCart.vue, I check if the reset prop is true and set the counter to 0;

Despite implementing these steps, it seems like it's not working as intended. Can you help me figure out what I'm missing?

Please visit this link for the complete code: Food Ordering App

Answer №1

If you need to pass the state across multiple components, there are various methods to achieve this goal. Here are three recommendations:

Centralized State management

To simplify handling of states, consider using a centralized state management tool like vuex: https://github.com/vuejs/vuex

This is especially beneficial for larger applications where passing the state through several component levels is required. It enhances efficiency and organization.

Property binding

A fundamental way to communicate with child components is through property binding. However, managing communication across multiple levels can become complex.

In such cases, you would include counter in the props array of both child components as follows:

foodList.vue (1. Level Child Component)

export default {
  props:['foods','reset', 'counter'],
 // ... your stuff
}

Include the component like this:

<foodList :counter="counter"></foodList>

addToCart.vue (2. Level Child Component)

export default {
  props:['food','reset', 'counter'],
 // ... your stuff
}

Finally, include the component like this:

<addToCart :reset="reset" :counter="counter"></addToCart>

Specify counter in the data object of your root component, then update it on a specific event. The state will trickle down.

App.vue

data() {
 return {
   // ... your stuff
   counter: 0,
 };
},
methods: {
 emptyCart:function(){
   // ... your stuff
   this.counter = 0; // reset the counter from your parent component
 }
}

Event Bus

For another option, utilize Vue's event bus. This is suitable for applications that become too intricate for simple property binding but are not extensive enough to warrant Centralized State management.

To begin, create a file named event-bus.js and add the following code:

import Vue from 'vue';
export const EventBus = new Vue();

You can then trigger events from the parent Component as shown below:

App.vue

import { EventBus } from './event-bus.js'; // check the path
export default {
 // ... your stuff
 methods: {
   emptyCart:function(){
     // ... your stuff
     EventBus.$emit('counter-changed', 0); // trigger counter-changed event
   }
 }
}

Subsequently, listen for the counter-changed event in your child component.

addToCart.vue

import { EventBus } from './event-bus.js';
export default {
 // ... your stuff
 created() {
   EventBus.$on('counter-changed', newCounter => {
     this.counter = newCounter;
   });
 }
}

Explore more about the event bus here: https://alligator.io/vuejs/global-event-bus/

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

The initialization of the Angular service is experiencing issues

I have a service in place that checks user authentication to determine whether to redirect them to the login page or the logged-in area. services.js: var servicesModule = angular.module('servicesModule', []); servicesModule.service('login ...

Utilizing Arrays for Angular Data Binding with AJAX

I am currently experimenting with loading Ajax data into an array and then binding the array using Angular. Here is my code (I have some experience with KO, so I'm keeping it simple for now): Update: I managed to get it working. I believe the issue w ...

Struggling to Align NAV buttons to the Right in React Framework

My current Mobile Header view can be seen here: https://i.stack.imgur.com/CcspN.png I am looking to achieve a layout similar to this, https://i.stack.imgur.com/pH15p.png. So far, I have only been able to accomplish this by setting specific left margins, ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...

Ways to retrieve the scroll position of content within an iframe

I have a webpage with an iframe that loads another webpage. <iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe> I am looking to retrieve the scroll position of the content inside the iframe using Jav ...

JavaScript Variables Lose Their Values

Similar Inquiry: How can I get the response from an AJAX call in a function? I have written a function that fetches numerical data from an online file. Although the file retrieval is successful (verified by the alert message), I encounter an issue whe ...

Troubleshooting Vue CLI installation

Currently in the process of learning Vue.JS and I've encountered an issue while attempting to install Vue CLI. My current versions are: NodeJS - v13.8.0 Vue CLI - v4.2.2 I had no trouble installing NodeJS, however, when I navigated to my folder in ...

How to convert table headings in Bootstrap-Vue.js

For a few nights now, I've been struggling to translate the table header in my vue.js component. It seems like I'm missing something as I'm new to Vue.js and can't seem to figure out what's wrong. Translating within the HTML works ...

Is three too much for the Javascript switch statement to handle?

I'm a beginner in Javascript and am working on a project to create a fun program involving astrological signs, planets, and houses to generate a story. I have included three switch statements within one function to accomplish this. I'm encounter ...

Submitting a file to the Slack API via the files.upload method using jQuery

I'm attempting to upload a file on a webpage and send it to Slack using the Slack API. Initially, my code looked like this: var request = require('request'); $(".submit").click(function(){ request.post({ url: 'https://slack.co ...

Creating designs on the canvas

With this code snippet, I have the ability to create lines using mouse points on a canvas. My goal is to identify when these lines connect to form a shape and then fill that shape with color. <script language="javascript" src="//ajax.googleapis.com/a ...

What is the most effective way to organize Vuex modules for optimal separation?

What is the most effective way to separate and structure the Vuex Store into modules from an architectural standpoint? I typically create a module for each major route when using Vue router. With this approach of dividing modules by Views, I often encount ...

What could be causing my HTML5 page to crash when accessed online, but not when viewed locally?

I am just getting started with HTML5 and decided to experiment with canvas. This is the first canvas page I have created. Everything works fine when I run the page locally (i.e. file:///), but once I upload the files to my webhost, the page gets stuck whi ...

How to determine if emit is present in Vue 3

Is there a way to determine if a specific emit has been passed to a Vue component using the composition API? Component A <Component @on-before-add="doSomeAction" /> Component B <Component /> <script setup> const emit = define ...

Utilizing the nested combination of map and filter functions

Struggling to grasp the concept of functional programming in JavaScript, my aim is to extract object boxart items with width=150 and height=200. Console.log(arr) the output shows [ [ [ [Object] ], [ [Object] ] ], [ [ [Object] ], [ [Object] ] ] ] I&apos ...

Argument contains an invalid left-hand side - Reference error

Currently, I have a straightforward JavaScript function in which I iterate over a series. After that, I add a value to an array and then assign it to an object. This process is part of my work on creating a c3 combination chart. However, I encountered an ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

Is it feasible to conceal a certain field once the user has chosen another field?

Looking to create an IF statement that will help me establish a specific rule. On a customer portal page, customers can open tickets via a form where they provide information such as "software product" and "environment" from dropdown lists, as well as othe ...