1
0
Эх сурвалжийг харах

support using state as function in root store as well

Evan You 8 жил өмнө
parent
commit
441762f79a
2 өөрчлөгдсөн 25 нэмэгдсэн , 3 устгасан
  1. 7 1
      src/store.js
  2. 18 2
      test/unit/store.spec.js

+ 7 - 1
src/store.js

@@ -11,11 +11,17 @@ export class Store {
     assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)
 
     const {
-      state = {},
       plugins = [],
       strict = false
     } = options
 
+    let {
+      state = {}
+    } = options
+    if (typeof state === 'function') {
+      state = state()
+    }
+
     // store internal state
     this._committing = false
     this._actions = Object.create(null)

+ 18 - 2
test/unit/store.spec.js

@@ -247,7 +247,7 @@ describe('Store', () => {
     expect(child.$store).toBe(store)
   })
 
-  it('should warn silent option depreciation', function () {
+  it('should warn silent option depreciation', () => {
     spyOn(console, 'warn')
 
     const store = new Vuex.Store({
@@ -263,7 +263,7 @@ describe('Store', () => {
     )
   })
 
-  it('strict mode: warn mutations outside of handlers', function () {
+  it('strict mode: warn mutations outside of handlers', () => {
     const store = new Vuex.Store({
       state: {
         a: 1
@@ -333,4 +333,20 @@ describe('Store', () => {
       })
     })
   })
+
+  it('should accept state as function', () => {
+    const store = new Vuex.Store({
+      state: () => ({
+        a: 1
+      }),
+      mutations: {
+        [TEST] (state, n) {
+          state.a += n
+        }
+      }
+    })
+    expect(store.state.a).toBe(1)
+    store.commit(TEST, 2)
+    expect(store.state.a).toBe(3)
+  })
 })