2016-12-25 20:16:30 +00:00
|
|
|
import Vue from 'vue'
|
|
|
|
import Vuex from 'vuex'
|
2017-05-13 17:32:11 +00:00
|
|
|
|
2016-12-25 20:16:30 +00:00
|
|
|
Vue.use(Vuex)
|
|
|
|
|
2017-05-13 17:32:11 +00:00
|
|
|
// Recursive find files in ~/store
|
|
|
|
const files = require.context('~/store', true, /^\.\/.*\.(js|ts)$/)
|
|
|
|
const filenames = files.keys()
|
|
|
|
|
|
|
|
// Store
|
|
|
|
let storeData = {}
|
|
|
|
|
|
|
|
// Check if store/index.js exists
|
|
|
|
if (filenames.indexOf('./index.js') !== -1) {
|
|
|
|
storeData = getModule('./index.js')
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store modules
|
|
|
|
if (!storeData.modules) {
|
|
|
|
storeData.modules = {}
|
|
|
|
}
|
2017-01-02 09:13:53 +00:00
|
|
|
|
2017-05-13 17:32:11 +00:00
|
|
|
for (let filename of filenames) {
|
|
|
|
let name = filename.replace(/^\.\//, '').replace(/\.(js|ts)$/, '')
|
|
|
|
if (name === 'index') continue
|
|
|
|
|
|
|
|
let namePath = name.split(/\//)
|
|
|
|
let module = getModuleNamespace(storeData, namePath)
|
|
|
|
|
|
|
|
name = namePath.pop()
|
|
|
|
module[name] = getModule(filename)
|
|
|
|
module[name].namespaced = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// createStore
|
2017-05-13 17:52:04 +00:00
|
|
|
export const createStore = storeData instanceof Function ? storeData : () => {
|
2017-05-13 18:52:37 +00:00
|
|
|
return new Vuex.Store(Object.assign({}, storeData, {
|
|
|
|
state: storeData.state instanceof Function ? storeData.state() : {}
|
|
|
|
}))
|
2017-05-13 17:45:42 +00:00
|
|
|
}
|
2017-05-13 17:32:11 +00:00
|
|
|
|
|
|
|
// Dynamically require module
|
2016-12-26 16:19:10 +00:00
|
|
|
function getModule (filename) {
|
2017-05-13 17:32:11 +00:00
|
|
|
const file = files(filename)
|
2017-05-13 17:45:42 +00:00
|
|
|
const module = file.default || file
|
2017-05-13 17:32:11 +00:00
|
|
|
if (module.state && typeof module.state !== 'function') {
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.error('[nuxt] store state should be a function.')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (module.commit) {
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.error('[nuxt] store should export raw store options instead of an instance.')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return module
|
2016-12-26 16:19:10 +00:00
|
|
|
}
|
|
|
|
|
2017-03-25 20:21:11 +00:00
|
|
|
function getModuleNamespace (storeData, namePath) {
|
2017-03-28 14:28:24 +00:00
|
|
|
if (namePath.length === 1) {
|
|
|
|
return storeData.modules
|
|
|
|
}
|
2017-03-25 20:21:11 +00:00
|
|
|
let namespace = namePath.shift()
|
|
|
|
storeData.modules[namespace] = storeData.modules[namespace] || {}
|
|
|
|
storeData.modules[namespace].namespaced = true
|
|
|
|
storeData.modules[namespace].modules = storeData.modules[namespace].modules || {}
|
|
|
|
return getModuleNamespace(storeData.modules[namespace], namePath)
|
|
|
|
}
|