Skip to content

Commit 441762f

Browse files
committed
support using state as function in root store as well
1 parent 8029c39 commit 441762f

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/store.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,17 @@ export class Store {
1111
assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)
1212

1313
const {
14-
state = {},
1514
plugins = [],
1615
strict = false
1716
} = options
1817

18+
let {
19+
state = {}
20+
} = options
21+
if (typeof state === 'function') {
22+
state = state()
23+
}
24+
1925
// store internal state
2026
this._committing = false
2127
this._actions = Object.create(null)

test/unit/store.spec.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ describe('Store', () => {
247247
expect(child.$store).toBe(store)
248248
})
249249

250-
it('should warn silent option depreciation', function () {
250+
it('should warn silent option depreciation', () => {
251251
spyOn(console, 'warn')
252252

253253
const store = new Vuex.Store({
@@ -263,7 +263,7 @@ describe('Store', () => {
263263
)
264264
})
265265

266-
it('strict mode: warn mutations outside of handlers', function () {
266+
it('strict mode: warn mutations outside of handlers', () => {
267267
const store = new Vuex.Store({
268268
state: {
269269
a: 1
@@ -333,4 +333,20 @@ describe('Store', () => {
333333
})
334334
})
335335
})
336+
337+
it('should accept state as function', () => {
338+
const store = new Vuex.Store({
339+
state: () => ({
340+
a: 1
341+
}),
342+
mutations: {
343+
[TEST] (state, n) {
344+
state.a += n
345+
}
346+
}
347+
})
348+
expect(store.state.a).toBe(1)
349+
store.commit(TEST, 2)
350+
expect(store.state.a).toBe(3)
351+
})
336352
})

0 commit comments

Comments
 (0)