Quellcode durchsuchen

expose replaceState()

Evan You vor 9 Jahren
Ursprung
Commit
49c17e15fa
3 geänderte Dateien mit 18 neuen und 4 gelöschten Zeilen
  1. 4 0
      docs/en/api.md
  2. 13 1
      src/index.js
  3. 1 3
      src/plugins/devtool.js

+ 4 - 0
docs/en/api.md

@@ -88,6 +88,10 @@ const store = new Vuex.Store({ ...options })
   })
   ```
 
+- **replaceState(state: Object)**
+
+  Replace the store's root state. Use this only for state restoration / time-travel purposes.
+
 - **watch(getter: Function, cb: Function, [options: Object])**
 
   Reactively watch a getter function's return value, and call the callback when the value changes. The getter receives the store's state as the only argument. Accepts an optional options object that takes the same options as Vue's `vm.$watch` method.

+ 13 - 1
src/index.js

@@ -75,7 +75,19 @@ class Store {
   }
 
   set state (v) {
-    throw new Error('[vuex] Vuex root state is read only.')
+    throw new Error('[vuex] Use store.replaceState() to explicit replace store state.')
+  }
+
+  /**
+   * Replace root state.
+   *
+   * @param {Object} state
+   */
+
+  replaceState (state) {
+    this._dispatching = true
+    this._vm.state = state
+    this._dispatching = false
   }
 
   /**

+ 1 - 3
src/plugins/devtool.js

@@ -8,9 +8,7 @@ export default function devtoolPlugin (store) {
   hook.emit('vuex:init', store)
 
   hook.on('vuex:travel-to-state', targetState => {
-    store._dispatching = true
-    store._vm.state = targetState
-    store._dispatching = false
+    store.replaceState(targetState)
   })
 
   store.on('mutation', (mutation, state) => {