vuex-local
Version:
Local state management within Vuex
40 lines (39 loc) • 1.61 kB
JavaScript
import { registerLocalModule, unregisterLocalModule } from './register';
import { mapLocalModule } from './map';
import { isObject, assert } from './utils';
export function applyMixin(Vue, options) {
var _a = options.parentModulePath, parentModulePath = _a === void 0 ? [] : _a;
Vue.mixin({
created: function () {
if (!this.$options.local)
return;
assert(this.$store, 'store must be injected');
ensureParent(this.$store, parentModulePath);
var localModule = this.$options.local.call(this);
var name = localModule.name;
assert(typeof name === 'string', 'local module name must be string');
assert(name !== '', 'local module name cannot be empty');
assert(isObject(localModule.state), 'state must be object');
var modulePath = this._localModulePath = parentModulePath.concat(name);
registerLocalModule(this.$store, modulePath, localModule);
// map the local module to this vm
mapLocalModule(this, modulePath, localModule);
},
beforeDestroy: function () {
if (!this.$options.local)
return;
unregisterLocalModule(this.$store, this._localModulePath);
}
});
}
function ensureParent(store, parentPath) {
var state = store.state;
var currentPath = [];
parentPath.forEach(function (key) {
state = state[key];
currentPath.push(key);
if (typeof state === 'undefined') {
store.registerModule(currentPath, {});
}
});
}