Write a simple vuex

Here is a simple Vuex Store example:

 
 
import { createStore } from 'vuex';

const store = createStore({
  state: {
    count: 0,
    message: 'Hello Vuex!'
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    setMessage(state, newMessage) {
      state.message = newMessage;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  },
  getters: {
    getCount(state) {
      return state.count;
    },
    getMessage(state) {
      return state.message;
    }
  }
});

export default store;

The Vuex Store in this example contains state, mutations, actions, and getters.

  • state Is where application state is stored and can be accessed in components.
  • mutations Functions are defined that modify the state. They receive an  state object as the first parameter and can be  commit triggered by calling a method.
  • actions Contains asynchronous operations or batch mutations, which can be  dispatch triggered by calling methods.
  • getters Provides methods for computing and accessing data stored in the state, using them like properties.

You can modify and extend it according to your business needs. When using the store in an application, you can storeaccess the state, mutations, actions, and getters defined in it by importing objects.

Guess you like

Origin blog.csdn.net/weixin_55209970/article/details/131963180