Nuxt/lib/app/store.js

65 lines
1.8 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)
2017-05-05 12:07:54 +00:00
let files = require.context('~/store', true, /^\.\/.*\.(js|ts)$/)
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) {
2017-03-28 14:28:24 +00:00
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) {
2017-05-05 12:07:54 +00:00
console.error('[nuxt.js] store/index should export raw store options instead of an instance.')
2016-12-25 20:16:30 +00:00
} else {
2017-05-02 06:57:39 +00:00
if (mainModule.state && typeof mainModule.state !== 'function') {
console.error('[nuxt.js] store state should be a function.')
}
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) {
2017-05-05 12:07:54 +00:00
let name = filename.replace(/^\.\//, '').replace(/\.(js|ts)$/, '')
2016-12-26 16:19:10 +00:00
if (name === 'index') continue
let namePath = name.split(/\//)
let module = getModuleNamespace(storeData, namePath)
name = namePath.pop()
module[name] = getModule(filename)
module[name].namespaced = true
2017-05-02 06:57:39 +00:00
if (typeof module[name].state !== 'function') {
console.error('[nuxt.js] store module state should be a function.')
}
2016-12-25 20:16:30 +00:00
}
}
2017-05-02 06:57:39 +00:00
export function createStore () {
return new Vuex.Store(storeData)
}