Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart.

I want to utilize this value to update another value in the template that is not part of the component. Is it achievable?

Below is the script for my parent Vue instance:

new Vue({
  el: "#cart-app",
  components: {
    cart: cartComponent
  },
  data: {
    searchQuery: '',
    appliedFilters: ['Day 1'],
    purchaseData: json,
    cCount: 0 // VALUE TO BE UPDATED BY COMPONENT
  }
});

Answer №1

If you're looking for the perfect scenario to utilize the .sync modifier, this is it.

According to the documentation:

When a prop with .sync is modified by a child component, the changes will be reflected in the parent component


In your specific situation, consider adding the .sync modifier to the cCount property that's being bound in the template (assuming that your component includes a cCount property):

<cart :c-count.sync="cCount"></cart>

Additionally, in the script section of the cart component, emit an update:cCount event whenever the count is incremented:

methods: {
  incrementCount() {
    this.cartCount++;
    this.$emit('update:cCount', this.cartCount);
  }
}

Doing this will automatically adjust the value of the cCount property in the parent Vue instance to match the value of the cartCount property within the cart component.

Check out this functional fiddle for reference.


Note that this functionality is supported from Vue version 2.3.0 onwards. However, if you are using an earlier version, you can achieve the same result using the following syntax:

<cart :c-count="cCount" @update:foo="val => cCount = val"></cart>

This is because

<comp :foo.sync="bar"></comp>
is essentially shorthand for:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

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

Angular 2+ Service for tracking application modifications and sending them to the server

Currently I am facing a challenge in my Angular 4 project regarding the implementation of the following functionality. The Process: Users interact with the application and it undergoes changes These modifications are stored locally using loca ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

Stop RequireJS from Storing Required Scripts in Cache

It seems that RequireJS has an internal caching mechanism for required JavaScript files. Whenever a change is made to one of the required files, renaming the file is necessary in order for the changes to take effect. The typical method of adding a version ...

Issue with pagination not functioning properly when using search functionality in vue-good-table

When using Vue-good-table remote search, I encountered an issue while searching on the second page. The search page automatically sets to the second page, but the pagination remains on the first page. I attempted to manually set the page using setCurrentPa ...

What is the best way to display the contents of an array that contains another array within it?

I need help looping through this array and displaying the "roleName" value. I want to use the map method to iterate over it. { "userMenuDTO": { "menuId": "13", "menuName":"PruebaMenu900 ...

Guide: Building a Dropdown Form in Angular 2

I have a webpage with an HTML form that includes a button positioned above the form. I am interested in adding functionality to the button so that when it is clicked, a duplicate of the existing form will be added directly beneath it. This will allow for m ...

Using Vanilla Javascript to implement a dark mode toggle button

I've been struggling with getting a button to properly switch a website to dark mode. I already have a night mode that works based on the user's location and time, so I know the issue lies within my JavaScript... Initially, I tried adding ' ...

Navigating through React-router with multiple child elements

Creating one of my routes requires the presence of two children in order to function properly. The main application page, where I set up all the routes, might look something like this: <Route path="/logs" component={Logs}> <Route path="/logs ...

What is the process for adding an event dynamically using a variable in programming?

Is there a way to dynamically add an event, such as @click, based on the value of another variable? I can't use a ref like this.$refs.example.addEventListner("click", someFunction) because I'm using it in a v-for I attempted something like @clic ...

Separating Vue.js 2 - taking out the HTML snippet from a single file component and placing it in its own

I was pondering if there is a method to divide a Single File Components file into smaller segments. What do I mean by this? Let's take a look: <template> ... </template> <script> export default { name: 'my-component&a ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

How can I use jQuery to reload the page only at certain intervals?

I'm currently using jQuery to reload a page with the code provided below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { window.location.reload(); }, 10000); }) & ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

Create 3000 unique squares using a procedural generation method

Looking to build a widget that consists of 3000 squares, but creating them manually would be extremely time-consuming. Does anyone have advice on how to efficiently generate the class .square 3000 times? Additionally, I need to have the ability to customiz ...

Using Javascript to fetch JSON data from a PHP file hosted on an IIS server, incorporating JSONP with

I have set up an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). The structure of the root directory is as follows: index.html, src/index.js, src/send_payment.php Currently, I am attempting to retrieve a basi ...

Identifying tick markers in the event loop of JavaScript and Node.js

Is there a way to determine if a function is called in the current tick or if it will be called in the next tick of Node.js event loop? For instance: function exampleFunction(callback){ // we can call callback synchronously callback(); // or we c ...

Display a modal following a successful HTTP request

As I reflect on this code, I can't help but cringe at its ugliness. Forgive me for what you are about to see! The goal is to make an HTTP request using Axios and then display a modal confirming that an email has been successfully sent. Currently, th ...

Express.js throwing an unexpected 404 error

I'm really struggling to understand why Node (express) only renders the index page and returns a 404 error for other pages, like "comproAffitto" in this example. In my app.js file: var index = require('./routes/index'); var comproAffitto= ...

Optimal code structuring for a javascript plugin

Hey there, I came across some intriguing posts on this topic, but I believe it's a very personal question that requires a tailored answer. So, I'm reaching out to ask you: what is the most effective way to organize my code for a JavaScript plugin ...