Reputation: 1361
Since Vue.js claims that it's a progressive framework, we tend to upgrade our online shopping to a Vue.js-backed SPA in small steps.
For example, we use Vue.js to render the mini-cart on the top of the page. And to make the order form dynamic. And to make the product details page dynamic, etc.
This means that we define many small vue applications on the same page.
However, they should still share the same context. Because when user clicks the buy
button on the product detail page, the shared context should be updated, so that the mini-cart on the top of the page would reflect the total number of products in the cart.
For this purpose, we created a global variable, and in our Vue.js mini-apps we use that as our data:
var cart = { orderLines: [], itemsCount: 0} // this is our global cart object
// this loads before any Vue code
Then, in mini-cart app we have:
var miniCart = {
data() {
return {
cart: cart // this is where we reuse the global cart object, to create a 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');
And then in our add to cart button we actually increase the cart.orderLines[i].quantity
.
However, mini-cart does not get updated.
What is wrong?
We're using Vue.js 3.
Upvotes: 1
Views: 143
Reputation: 138276
Your repro shows that you have a script external to your Vue apps that modifies cart
.
In order for that modification to be reactive, you need to create cart
with Vue.reactive()
:
const cart = Vue.reactive({ orderLines: [], itemsCount: 0 })
Upvotes: 2