Guide to sharing a global object among multiple Vue.js mini apps within the same page

As we embrace the progressive nature of Vue.js, we are gradually transitioning our online shopping experience into a Vue.js-powered Single Page Application (SPA).

One step at a time, we implement Vue.js to render specific components such as the mini-cart at the page's top, dynamic order forms, and product details pages.

This approach results in multiple small Vue applications coexisting on the same page while still sharing a common context. This shared context is crucial for ensuring that interactions like clicking the buy button on a product detail page update the overall cart state reflected in the mini-cart.

To achieve this synchronization, we established a global variable serving as our universal cart object, integrated across all Vue.js mini-apps:

var cart = { orderLines: [], itemsCount: 0} // global cart object
// initializes before any Vue code

In the mini-cart application, we utilize this global cart object to maintain a unified context:

var miniCart = {
    data() {
        return {
            cart: cart // utilizes global cart object to ensure shared context
        }
    },
    computed: {
        itemsCount() {
            var _this = this;
            var itemsCount = 0;
            for (var i = 0; i < _this.cart.orderLines.length; i++) {
                itemsCount += _this.cart.orderLines[i].quantity || 0;
            }
            return itemsCount;
        }
    },
    methods: {

    }
};
Vue.createApp(miniCart).mount('#miniCart');

When adding items to the cart through the add to cart button, the corresponding cart.orderLines[i].quantity increments accordingly. Yet, we encounter an issue where the mini-cart fails to reflect these updates.

What could be causing this discrepancy?

Note: Our implementation is based on Vue.js version 3.

Answer №1

The demonstration you provided in your sample code reveals that an external script is altering the cart object in your Vue applications.

To ensure that this alteration triggers reactivity, it is essential to initialize the cart object using Vue.reactive() as shown below:

const cart = Vue.reactive({ orderLines: [], itemsCount: 0 })

For a practical illustration, refer to this demonstration.

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 XMLHttpRequest response states that the preflight request did not meet the access control check requirements

I am attempting to subscribe to a firebase cloud messaging topic by sending an http post request. var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

there is no minimum height specified for the table

Hey there! I'm working on a dynamic table that I populate using data from my API. However, I'm facing an issue where I want the table to maintain a minimum height when there are only a few results, but I can't seem to make it work. I attemp ...

Animating the smooth collapse of panels within listviews

I have successfully implemented a smooth animation code for a collapsible panel, and it is working wonderfully: <script type="text/javascript"> function pageLoad(sender, args) { smoothAnimation(); } function smoothAnimation() ...

How to upload numerous chosen files from an Android device using PHP script

When attempting to upload multiple files using the file selection option on an Android mobile device, I encountered an issue of not being able to select specific multiple files. I tried utilizing the multiple-form/data and multiple="multiple" attributes w ...

Enhance your React Native app: Utilizing dynamic string variables with react-native-google-places-autocomplete query

I have encountered an issue while attempting to pass a dynamic country code to restrict search results. Here is the code in question: let loc = 'de' <GooglePlacesAutocomplete placeholder="Search" autoFocus={true} onPress ...

Develop a RESTful API in Node.js that allows for the sending of audio files along with JSON

My current project involves a REST API that I've built using node and express. I'm now facing a challenge where I need to send both JSON Data and an Audio File in a single http request. The audio file needs to be playable on the client side. JSO ...

What are some strategies for stopping a form from redirecting me while utilizing ReactJS and ExpressJS?

Recently, I created a form that redirects to the route /repair upon submission with an action of /repair. However, I would prefer to keep it as a Single Page Application (SPA) where after submitting the form, the fields are cleared, and a simple message l ...

Add a document to MongoDB and then tailor the data using a separate query before insertion

My request is quite simple: I need to add a new document to my MongoDB database. However, before doing so, I must first check if the slug already exists in the database. If it does, I need to rename the slug before proceeding with the insertion. I have b ...

Extracting the call from REST API in JSON format

Working with a third-party database using a REST API, I encountered an error response (as expected). Here is the code snippet: transaction.commit(function(err) { if (err){ var par = JSON.parse(err); \\ leading to error: SyntaxError: Unexpecte ...

Interact with HTML Radio Buttons to Trigger Input Opening

I need to have a message saying "We're sorry..." and a "black box" displayed only when the radio button is set to YES, otherwise keep it hidden. Can I achieve this using JavaScript only, or is there a way to do it with HTML alone? <h3 >Did you ...

Breaking apart faces of a sphere using Three.js

I am currently working on creating a sphere geometry. geometry = new THREE.SphereGeometry( 200, 20, 10 ); material = new THREE.MeshLambertMaterial({ shading: THREE.FlatShading, color: 0xff0000 }); sphere = new THREE.Mesh(geometry, material); scene.add( sp ...

How can I terminate a parent function in NodeJS when inside a virtual function?

Here is something similar to the code snippet below: var async = require(async) function start () { async.series( [ function (callback) { // do something callback(null, "Done doing something") ...

Troubleshooting Issue with JQuery Date Picker: Date Not Valid

Encountering an issue when using the date from JQuery DatePicker in an SQL Statement variable, resulting in an error of invalid datetime string. Even after attempting to format it with DateTime.Parse or Convert.DateTime. JQuery DatePicker <script> ...

Tips for sending a Postgres Pool or Client over a socket

After deploying my server to Heroku, I encountered an issue with sending a request to my Raspberry Pi for running a scraping function and updating a table in the Heroku Postgres database. The problem seems to be related to the client.query() function not b ...

Incorporating database coordinates into Marker React Leaflet: A Step-by-Step Guide

When I retrieve coordinates from the database, they are structured as "lat" and "lon" fields. In my mapping application, I have multiple markers to display. How can I combine these two fields to pass coordinates (coord.lat and coord.lon) to the Marker comp ...

Troubleshooting error: Unable to access property 'post' in Angular Service when using $http

As I delve into learning Angular, my approach involves shifting all the business logic to services. However, I encountered an error while attempting a post request within a service: Cannot read property 'post' of undefined Provided below is a ...

Struggling with Passport.js authentication on a Vue.js live-reload server and Node server in a development environment

UPDATE: I'm encountering an issue with my Vue frontend not setting the session cookie Objective: To enable Login with Twitch and establish synchronized authenticated sessions between the frontend and backend systems Description: I am facing diffic ...

Tips for showing multiple autocomplete entries in a text box following a successful AJAX request

I'm having an issue with my code where the autocomplete multiple values, successfully retrieved by Ajax, are not being displayed. Here is the HTML I am using for display: <input type="text" name="s_to" id="s_to" class="controls"> Here is my jQ ...

I want to save the information for "KEY" and "textValue" in JSON format and then return it as a response when I make a request to app.get("/api"). How can I achieve this?

Working with GCP Document AI using Node.js and react.js, I have created a JSON structure (var jsonResult) in the provided code. In the for loop, I am extracting key and text value data by using console.log(key); and console.log(textValue);. However, my g ...