I have a simple cart demo.
It has 3 Vue applications, a global object as a shared context, and a button that is in Vanilla JS.
If you add products to the cart via a Vue app, everything works.
But if you use the Vanilla JS button, nothing works.
Basically, I want to change the global object outside the Vue application, and then somehow force the view to capture the changes.
How can I do that?
P.S. the reason I'm doing this is because I'm using Vue.js progressively in a new application. Part of is jQuery, and part of it Vue. They both manipulate a global object as a shared object.
This is my JS code:
let cart = { orderLines: [], itemsCount: 0 }
let addViaJs = document.querySelector('#addViaJs');
addViaJs.addEventListener('click', () => {
cart.orderLines[0].quantity += 1; // this line does not cause update in UI
});
let miniCart = {
data() {
return {
cart,
}
},
computed: {
itemsCount() {
let itemsCount = 0;
for (let i = 0; i < this.cart.orderLines.length; i++) {
itemsCount += this.cart.orderLines[i].quantity || 0;
}
return itemsCount;
}
},
};
Vue.createApp(miniCart).mount('#miniCart');
let bigCart = {
data() {
return {
cart,
}
},
computed: {
itemsCount() {
let itemsCount = 0;
for (let i = 0; i < this.cart.orderLines.length; i++) {
itemsCount += this.cart.orderLines[i].quantity || 0;
}
return itemsCount;
}
},
};
Vue.createApp(bigCart).mount('#bigCart');
let productList = {
data() {
return {
cart,
products: [
{ id: 1, label: 'Product A' },
{ id: 2, label: 'Product B' },
{ id: 3, label: 'Product C' },
]
}
},
methods: {
addToCart(product) {
const line = this.cart.orderLines.find(line => line.id === product.id);
if (line) {
line.quantity++;
} else {
this.cart.orderLines.push({ ...product, quantity: 1 });
}
},
}
};
Vue.createApp(productList).mount('#productList');