Vuex Documentation

website·Indexed 19 days ago

https://vuex.vuejs.org/

Official documentation for Vuex 4, the state management library for Vue 3. It covers core concepts including a single state tree, getters, mutations, actions, and modules. The guide provides detailed instructions on installation, TypeScript support, Composition API integration via useStore, strict mode, plugin development, and migrating from Vuex 3.x to 4.0.

Tokens
22K
Snippets
138
Records
160
Agent score
90%

What's inside Vuex

  1. Overview of Vuex state management

    Vuex is a state management pattern and library designed for Vue.js applications. It provides a centralized store for all components in an application, ensuring that the state can only be mutated in a predictable manner. It is inspired by Flux, Redux, and The Elm Architecture, but is specifically tailored to leverage Vue.js's granular reactivity system for efficient updates. Vuex 4 is the version compatible with Vue 3.
  2. Understand the role of Vuex Actions

    Actions are similar to mutations, but with two key differences: instead of mutating the state directly, actions commit mutations; and actions can contain arbitrary asynchronous operations. Action handlers receive a context object that provides access to commit, state, getters, and dispatch (to trigger other actions).
    const store = createStore({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      actions: {
        increment ({ commit }) {
          commit('increment')
        }
      }
    })
  3. Understand Vuex core architectural principles

    Vuex enforces three high-level principles to manage application state:

    1. Application-level state must be centralized in the store.
    2. State can only be mutated by committing mutations, which are required to be synchronous transactions.
    3. Asynchronous logic must be encapsulated within actions, which can also be composed together.
  4. Understand the Vuex state management pattern

    Vuex provides a centralized store for all components in a Vue.js application. It implements a "one-way data flow" pattern to ensure state mutations are predictable. This solves common problems in large applications such as:

    • Prop Drilling: Avoiding the need to pass props through deeply nested components.
    • Sibling Communication: Allowing sibling components to share state without complex event emitting or parent references.
    • State Synchronization: Preventing brittle code caused by mutating multiple copies of the same state across different components.
  5. Understand the Vuex Single State Tree concept

    Vuex uses a single state tree—a single object that contains the entire state of the application, serving as the 'single source of truth'. This architecture simplifies locating specific state parts and enables easy capturing of state snapshots for debugging. While the state is centralized, it can still be organized into sub-modules for modularity. State data must be simple objects, following the same rules as Vue instance data.
  6. Use constants for mutation types

    Using constants for mutation types helps with linting and provides a centralized overview of all possible mutations in an application. This is typically implemented using ES2015 computed property names in the store configuration.
    // mutation-types.js
    export const SOME_MUTATION = 'SOME_MUTATION'
    
    // store.js
    import { createStore } from 'vuex'
    import { SOME_MUTATION } from './mutation-types'
    
    const store = createStore({
      state: { ... },
      mutations: {
        [SOME_MUTATION] (state) {
          // mutate state
        }
      }
    })
  7. Understand Vuex core architectural principles

    Vuex does not enforce a strict code structure but requires adherence to three high-level principles to maintain predictable state management:

    1. Application-level state is centralized in the store.
    2. State can only be changed by committing mutations, which are synchronous transactions.
    3. Asynchronous logic must be encapsulated and can be composed using actions.
  8. Understand the Vuex Store concept

    A Vuex store is a centralized container for an application's state. It differs from a standard global object in two key ways:

    1. Reactivity: Vue components that consume the store state update automatically and efficiently when the state changes.
    2. State Mutation: Store state cannot be changed directly. State changes must be performed by explicitly committing mutations, which ensures a traceable record of all changes and enables debugging tools like time-travel debugging.
  9. Understand the Vuex Store concept

    A Vuex store is a centralized container for application state. It differs from a plain global object in two key ways:

    1. It is reactive: Vue components that retrieve state from the store will automatically update when that state changes.
    2. State is immutable from the outside: You cannot mutate the store's state directly. State changes must be performed by explicitly committing mutations, which ensures all changes are trackable and enables debugging tools like state snapshots and time-travel debugging.
  10. Understand the Vuex Single State Tree

    Vuex uses a single state tree, meaning a single object contains all application-level state to serve as the 'single source of truth.' This simplifies locating state and enables easy snapshots for debugging. The state object must be plain, following the same rules as the data option in a Vue instance.
  11. Initialize Vuex 4 store using createStore

    To align with the Vue 3 initialization process, Vuex 4 introduces the createStore function. While new Store(...) still works, using createStore is the recommended approach for compatibility with Vue 3 and Vue Router Next.
    import { createStore } from 'vuex'
    
    export const store = createStore({
      state () {
        return {
          count: 1
        }
      }
    })
  12. Handle form inputs with Vuex state in strict mode

    When Vuex is in strict mode, using v-model directly on a piece of state (e.g., <input v-model="obj.message">) will cause an error because v-model attempts to mutate the state directly outside of a mutation handler. To resolve this, bind the input value manually and trigger a Vuex mutation via an event handler like @input or @change.
    <template>
      <input :value="message" @input="updateMessage">
    </template>
    
    <script>
    import { mapState } from 'vuex'
    
    export default {
      computed: {
        ...mapState({
          message: state => state.obj.message
        })
      },
      methods: {
        updateMessage (e) {
          this.$store.commit('updateMessage', e.target.value)
        }
      }
    }
    </script>
    
    // In the Vuex store:
    mutations: {
      updateMessage (state, message) {
        state.obj.message = message
      }
    }