VueJS: Manage shopping cart in VueApp with Vuex and?

Tram Ho

Hello everyone, today I continue to write about VueJS, and this time I will introduce to you the extremely cool package that I use in the project about VueJS. These are vuex-shared-mutations .

1. Introduction:

Looking at the package name, you know what vuex-shared-mutations used for, right?

Share certain Vuex mutations across multiple tabs / windows.

vuex-shared-mutations will basically sync vuex in your site between tabs and windows.

Why do mình need to sync vuex ?

Let’s look at a basic problem:

I will use Lazada as an example. We temporarily consider Lazada’s shopping cart as 1 Store in Vuex .

Try to log into Lazada , leave your shopping cart empty, then choose to open any 3 products to a new tab. In tab 1, we choose THÊM VÀO GIỎ HÀNG . Shopping cart will change from 0 -> 1 . Then on the 2nd tab, we will choose THÊM VÀO GIỎ HÀNG , this time the total product will be 0 -> 2 . First, this is a bad UX for me personally. Fortunately, when updating the shopping cart, Lazada called the API to get the latest data, and since the shopping cart is attached to the user, we will have a total of 1 , then add X new products . Try in case we have 1 VueApp not logged in yet but still allow the purchase? Data in Vuex now cannot cross tabs / window. No, the data can now cross tabs / windows, thanks to vuex-shared-mutations .

2. Config vuex-shared-mutations :

I wrote a simple app to synchronize the counter counter as follows.

In the file store/index , I will write the full actions, mutations, state properties:

We simply create a store with a symbolic counter variable. At this point, if you open 2 different tabs, you can see that the 2-page data is 2 different stores. Now let’s add vuex-shared-mutations to our store:

In the createMutationsSharer({ predicate: ["increment"] }) , you pass the mutaion name that you will listen to, and vuex-shared-mutaions will automatically update vuex based on the mutations selected.

Demo:

  1. vuex-shared-mutations :

  1. When there are vuex-shared-mutations :

My article is over here. Thank you everyone for watching.

Share the news now

Source : Viblo