Ways to exchange information among Vue components?

My role does not involve JavaScript development; instead, I focus on connecting the APIs I've created to front-end code written in Vue.js by a third party. Currently, I am struggling to determine the hierarchy between parent and child elements when accessing the 'shopping cart' to send details to a server. The flow of actions is as follows:

  • A. Select a concession
  • B. Choose an item to add to the cart
  • C. Proceed to the cart
  • D. Checkout

The following code snippet represents the Product Card section:

<template>
    <div class="flex flex-col flex-wrap justify-center items-center w-1/3 px-12">
        <img :src="require(`../../assets/images/` + backgroundImg)" :alt="product.id"> 
        <h5 class="font-bold text-lg mt-2">{{ product.title }}</h5>
        <p class="text-15px text-gray-500 ">{{ product.short }}</p>
        <p class="text-15px text-gray-500 px-8">{{ product.long }}</p>
        <p class="text-base font-bold">${{ formatPrice(product.price) }}</p>
        <Button @click.native="$emit('add-cart', product)"  msg="Add to Cart" class="bg-seafoam rounded-md lg:text-sm lg:px-8 text-white mt-1"></Button>
    </div>
</template>

<script>
import Button from '../Button.vue';

export default {
    name: 'ProductCard',
    components: {
        Button
    },
    props: {
        product: Object
    },
    data() {
        return {
            backgroundImg: this.product.image,
        }
    },
    methods: {
        formatPrice(value) {
        let val = (value/1).toFixed(2)
        return val.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2,})
        }
    }
}
</script>

In the Product List code below, various sections such as Menu Heroes, Cart Heroes, and Checkout Heroes are managed:

<template>
...

Next, we have the Cart List code where the items in the cart and their total prices are displayed:

<template>
...

The Cart Widget Code consists of a widget showing the number of items in the cart along with the total price:

<template>
...

Below is the code for cart cards displaying information about each item in the cart:

<template>
...

Lastly, the Checkout code handles contact and delivery information needed for placing an order:

<template>
...

</template>

<script>
...
</script>

I am looking to access items stored in the cart in order to make a POST call to the server. However, I'm facing challenges in achieving this. Any guidance would be greatly appreciated.

Just to clarify, the 'Product' object contains properties such as id, title, short description, long description, price, and a default quantity of 1.

Answer №1

The shopping cart is defined within the ProductList component. As the parent component, it houses and manages all other child components. By assigning the :cart="cart" property, the cart can be distributed to all other components for access. Child components simply need to include cart in the props they receive:

props: {
  cart: Array
}

This enables easy access to this.cart within the child component.

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

Using AngularJS and ServiceStack webservice, perform the "get('url')" operation

I'm completely new to AngularJS and I'm attempting to retrieve some JSON items from a webservice I quickly set up using ServiceStack. When I enter the URL in the browser, I can see the JSON object without any issues. However, for some reason Angu ...

Accessing the API located on the identical server as the VUE application

Attempting to access the API located at (hosted on domain 127.0.0.1) from a Vue app with the following Apache configuration: <VirtualHost *:80> ServerAdmin <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd2ded6d3ffd2ded ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

Watch an Instagram video retrieved from a public API and enjoy the content!

I've been exploring solutions on SO for displaying Instagram videos using the public api ?__a=1 method. While I came across a helpful question that pointed me in the right direction, I still faced some challenges. Once I retrieve user media, I check ...

Using AJAX POST requests with PHP and SQL queries seems to function properly but unfortunately, it only

I am facing an issue with deleting an item from a list using AJAX, PHP, and MySQL. The first time I try to delete an item, the AJAX request works perfectly. However, on subsequent attempts, although the AJAX request returns success, the item is not deleted ...

Struggling to retrieve information from session storage to pass along to a PHP class

Is there a way to fetch the email of the currently logged-in user from sessionStorage and send it to a PHP file? I have tried implementing this, but it seems to be not functioning properly. Could you assist me in resolving this issue? <?php $mongoCl ...

Vue routing with navigation bar and side panel

I'm currently working on implementing a routing system using Vue. Specifically, I am looking to have a fixed navbar displayed at the top of every page, as well as a sidebar that is only visible on the settings page. Following the guidance provided in ...

Accessing iframe's HTML using a server-side solution by circumventing the Cross-Domain Policy

Our current challenge involves accessing dynamically generated HTML elements using JavaScript, particularly when trying to extract image URLs from these elements. When the HTML elements are generated solely through JavaScript, extracting the URL is straigh ...

"Unlock the Power of VueJS 2 with Dynamic Templates

Just starting out as a VueJS student! I created a "MainTemplate.vue", which includes a menu, footer, header... Then I decided to create another .vue file named "ComponentB.vue". Here is the content of my ComponentB.vue file: <template> <h ...

Discover the step-by-step guide for inserting personalized HTML into the current widget screen on Odoo 12 with

For the past 3 days, I've been stuck trying to figure out how to print order items. My goal is to have a custom HTML code added to a div with the class 'order-print' when the Order button is clicked. I am using odoo 12 and facing issues wit ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

Fetching the exchanged messages between the sender and recipient - utilizing MongoDB, Express, and React for chat functionality

I am dealing with two collections named students and teachers in the mongodb database. The structure of a conversation between a student and a teacher involves arrays of messages within each object, as well as the IDs of the sender and receiver. I am seeki ...

Is it possible to integrate an "inline-template" component within another "inline-template" component?

I seem to be facing a roadblock in my project. I believe there might be a missing step or this task is simply impossible. I can't seem to wrap my head around it. Inline-templates offer the advantage of utilizing Laravel Blade syntax and harnessing th ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

Filtering objects in JavaScript using a technique similar to list comprehension

I'm dealing with a basic array structure that resembles: obj = {1:false, 2:true, 3:true} My goal is to extract an array containing all the keys in the object that have a value of true. In Python, you can achieve this easily using: >>> [ke ...

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

Issue with delayed chaining of class addition and removal in JQuery not functioning as expected

Here is the code snippet: $(document).ready(function () { $('.current-visitors').delay(3000).queue(function () { $(this).addClass('show').delay(1000).queue(function () { $(this).removeClass('sho ...

Vitest tests encounter issues due to the customized $reset pinia store method in the setup syntax

I have developed a custom plugin to mimic the $reset method found in Options API syntax for setup syntax within my Vue application. The plugin code is as follows: import cloneDeep from 'lodash.clonedeep'; import type { Store } from 'pinia&a ...