Nuxt/lib/app/store.js

58 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-12-25 20:16:30 +00:00
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let files = require.context('~/store', true, /^\.\/.*\.js$/)
2017-02-03 14:09:27 +00:00
let filenames = files.keys()
2017-01-02 09:13:53 +00:00
2016-12-26 16:19:10 +00:00
function getModule (filename) {
let file = files(filename)
return file.default
? file.default
: file
}
function getModuleNamespace (storeData, namePath) {
if (namePath.length == 1) return storeData.modules
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)
}
2016-12-26 16:19:10 +00:00
let store
let storeData = {}
2016-12-25 20:16:30 +00:00
2016-12-26 16:19:10 +00:00
// Check if store/index.js returns a vuex store
2017-01-02 09:50:18 +00:00
if (filenames.indexOf('./index.js') !== -1) {
2016-12-26 16:19:10 +00:00
let mainModule = getModule('./index.js')
if (mainModule.commit) {
store = mainModule
2016-12-25 20:16:30 +00:00
} else {
2016-12-26 16:19:10 +00:00
storeData = mainModule
}
}
// Generate the store if there is no store yet
if (store == null) {
storeData.modules = storeData.modules || {}
2017-01-02 09:13:53 +00:00
for (let filename of filenames) {
2016-12-26 16:19:10 +00:00
let name = filename.replace(/^\.\//, '').replace(/\.js$/, '')
if (name === 'index') continue
let namePath = name.split(/\//)
let module = getModuleNamespace(storeData, namePath)
name = namePath.pop()
module[name] = getModule(filename)
module[name].namespaced = true
2016-12-25 20:16:30 +00:00
}
2016-12-26 16:19:10 +00:00
store = new Vuex.Store(storeData)
2016-12-25 20:16:30 +00:00
}
2016-12-26 16:19:10 +00:00
export default store