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.