Chuyển đến nội dung

Bài 32 · Migration from Vuex

Migrating a Vuex Module to Pinia Step by Step

Convert a real namespaced Vuex cart module into a Pinia store in clear steps, handle rootState and cross-module calls, and prove the behavior is identical.

The mapping lesson showed the dictionary. Now we translate a realistic module, one decision at a time. The module is a namespaced shopping cart that uses state, getters, mutations, async actions, rootState and rootGetters. At the end, a small script runs the same scenario against both versions and compares the results, which is the best way to trust a migration.

The starting point: a Vuex module

JavaScript
// store/modules/cart.js (Vuex 4)
export default {
  namespaced: true,
  state: () => ({
    items: [],            // { id, name, price, qty }
    status: "idle",
  }),
  getters: {
    count: (state) => state.items.reduce((n, i) => n + i.qty, 0),
    subtotal: (state) => state.items.reduce((s, i) => s + i.price * i.qty, 0),
    total(state, getters, rootState) {
      return getters.subtotal * (1 - rootState.user.discount);
    },
  },
  mutations: {
    ADD_ITEM(state, product) {
      const found = state.items.find((i) => i.id === product.id);
      if (found) found.qty++;
      else state.items.push({ ...product, qty: 1 });
    },
    REMOVE_ITEM(state, id) {
      state.items = state.items.filter((i) => i.id !== id);
    },
    SET_STATUS(state, status) { state.status = status; },
    CLEAR(state) { state.items = []; },
  },
  actions: {
    addItem({ commit }, product) { commit("ADD_ITEM", product); },
    async checkout({ commit, getters, dispatch }) {
      commit("SET_STATUS", "paying");
      await dispatch("payments/charge", getters.total, { root: true });
      commit("CLEAR");
      commit("SET_STATUS", "done");
    },
  },
};

Step 1: create the store and copy the state

Name the file stores/cart.js, export useCartStore, use the module name as the id, and copy state as it is:

JavaScript
export const useCartStore = defineStore("cart", {
  state: () => ({
    items: [],
    status: "idle",
  }),
});

Step 2: copy the getters, replace getters and rootState

Getters keep their shape. The second argument of a Vuex getter (getters) becomes this, and rootState.user becomes a call to the user store:

JavaScript
getters: {
  count: (state) => state.items.reduce((n, i) => n + i.qty, 0),
  subtotal: (state) => state.items.reduce((s, i) => s + i.price * i.qty, 0),
  total() {
    const user = useUserStore();
    return this.subtotal * (1 - user.discount);
  },
},

Use a regular function (not an arrow) when you need this. In TypeScript, add an explicit return type to getters that use this.

Step 3: turn mutations into plain code

Every mutation is a function of (state, payload). Move its body into whichever action needs it. If a mutation is only used by one action, inline it. If several actions share it, make it an action. Many tiny mutations such as SET_STATUS disappear and become an assignment:

JavaScript
actions: {
  addItem(product) {
    const found = this.items.find((i) => i.id === product.id);
    if (found) found.qty++;
    else this.items.push({ ...product, qty: 1 });
  },
  removeItem(id) {
    this.items = this.items.filter((i) => i.id !== id);
  },
},

Step 4: rewrite async actions

commit becomes assignment, dispatch(..., { root: true }) becomes a call to the other store, and getters.total becomes this.total:

JavaScript
async checkout() {
  const payments = usePaymentsStore();
  this.status = "paying";
  await payments.charge(this.total);
  this.items = [];
  this.status = "done";
},

Step 5: update the callers

Before After
this.$store.dispatch("cart/addItem", p) cart.addItem(p)
this.$store.getters["cart/total"] cart.total
this.$store.state.cart.items cart.items
mapGetters("cart", ["total"]) mapState(useCartStore, ["total"])
mapActions("cart", ["checkout"]) mapActions(useCartStore, ["checkout"])

(In <script setup>, use const cart = useCartStore() and wrap state in storeToRefs() if you destructure.)

Prove they behave the same

This page runs the original Vuex module and the migrated Pinia store with the same scenario: add a pen twice, add a book, apply a discount of 10 percent, check out and compare every observable value. Both modules are exactly the ones shown above, with a fake payments service that records the amount. Vuex is the real Vuex 4 library; the "user" module is a one-field stand-in.

Vuex module vs migrated Pinia store: identical behavior

Both columns match in every row. If you find yourself migrating a big module, write this kind of comparison first (even as a Vitest test) and keep it until the migration is finished.

Things to watch for

  • strict mode. Vuex's strict: true hid accidental writes. In Pinia they are legal, so review code that mutated store.state from components.
  • Module state shape. store.state.cart.items becomes cart.items. Search the whole project for state.cart, getters["cart/ and "cart/.
  • Action return values. Vuex dispatch always returns a promise. Pinia actions return whatever you return: await them if callers need to wait.
  • commit with { root: true } from a module into another: replace with a call on the other store.
  • Naming. Mutation names (ADD_ITEM) were constants; action names are normal verbs (addItem).
  • Persistence plugins (vuex-persistedstate) are replaced with Pinia plugins such as persistedstate.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does a Vuex getter's second argument (getters) become in a Pinia getter?

    In Pinia a getter that is a regular function uses this to reach other getters and state.
  2. 2. How is commit('SET_STATUS', 'paying') written in a Pinia action?

    Actions change state by assignment.
  3. 3. Why is it useful to run the same scenario against the old and the new store?

    A side-by-side comparison catches differences in getters, status values and amounts before you delete the old module.
  4. 4. What replaces dispatch('payments/charge', amount, { root: true })?

    Import and call the other store; no root flag or namespace string is needed.

Summary

  • Migrate one module at a time: state, then getters, then mutations folded into actions, then async actions.
  • getters argument becomes this; rootState and { root: true } become calls to other stores.
  • Update every caller: dispatch, getters and state paths, map helpers.
  • Compare old and new behavior with the same scenario.
  • Review code that relied on Vuex strict mode.

Next: Migrating Components and Coexisting with Vuex

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.