MY notebook

Vuex 3

Published on Dec 2, 2021

resource:documentationvuevuex

Source

Introduction

  • state management pattern + library for Vue
  • for medium to large scale SPA
  • solve problems
    • multiple views depending on same piece of state
    • actions from different views need to mutate the same piece of state
  • reactive
  • can only mutate state through commiting mutations

Core Concepts

State

  • single state tree, so one store for each application
  • provide store in root instance to inject store into all child components. Can be access through this.$store
  • mapState is for mapping multiple store state properties ('count' = map this.count to store.state.count)
  • spread it when use with local computed properties

Getters

  • like computed property for store. When we need to value from computing a state
  • evaluate based on dependencies
  • access via this.$store.getters
  • arguments: state, getters?
  • method-syle allows passing arguments to getter
  • spread mapGetters in computed

Mutations

  • only way to change state
  • has a type and a handler (perform actual state modification)
  • store.commit(<type>, payload?) OR store.commit(type: <type>, <payload>: value). payload should be an object
  • follows reactivity rules
    • initial state
    • Vue.set OR replace the whole object
  • constant for type in large project
  • must be synchronous
  • mapMutations

Actions

  • commit mutations
  • can be asynchronous
  • receive context object and also payload?
  • store.dispatch
  • mapActions
  • can then on dispatch to chain actions

Modules

  • each module can has its own store, even nested modules
  • local state is the first argument.
  • actions has context.state and context.rootState (arguments: state, commit, rootState?, rootGetters?). Same thing for getters
  • actions, mutations, and getters are registered under the global namespace. Use namespace:true to registers them under module
  • pass {root: true} as third argument to dispatch and commit to trigger actions in the global namespace
  • can register global actions in namespaced module using handler and {root:true}
  • can pass module namespace when mapping to save keystrokes OR createNamespaceHelpers
  • look out for namespace when developing plugin
  • store.registerModule to register a module after store is created. Can unregisterModule and hasModule
  • preserveState

Advanced

Application Structure

  • store has the application-level state
  • only mutate using mutation and keep it sync
  • use actions to do async stuff

Plugins

  • plugins when creating store
  • a function that only receives store

Strict Mode

  • strict:true
  • do not enable for production because can be expensive

Form Handling

  • bind value and @input OR get and set

Testing

  • mutation: export mutation itself
  • action: mock
  • getter: same as mutation

Hot Reloading

  • supports hot-reloading mutations, modules, actions and getters during development