diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..7b215c0fc --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +github: [yyx990803, kiaking, ktsn] +open_collective: vuejs +patreon: evanyou diff --git a/CHANGELOG.md b/CHANGELOG.md index ec01b52aa..1ea2e51ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,26 @@ +## [3.6.2](https://github.com/vuejs/vuex/compare/v3.6.1...v3.6.2) (2021-01-26) + +### Bug Fixes + +* **build:** fix wrong path name for the export module ([679313b](https://github.com/vuejs/vuex/commit/679313bf5e4de066f340a06ef9bfe08d1536fadd)) + +## [3.6.1](https://github.com/vuejs/vuex/compare/v3.6.0...v3.6.1) (2021-01-26) + +### Bug Fixes + +* fix tree shaking notworking in webpack bundle ([#1906](https://github.com/vuejs/vuex/issues/1906)) ([1dc2d1f](https://github.com/vuejs/vuex/commit/1dc2d1f21de42138053ea3281dde05487642a76d)) + +# [3.6.0](https://github.com/vuejs/vuex/compare/v3.5.1...v3.6.0) (2020-11-25) + +### Bug Fixes + +* stop throwing an error on `hasModule` when parent does not exists ([#1850](https://github.com/vuejs/vuex/issues/1850)) ([#1851](https://github.com/vuejs/vuex/issues/1851)) ([12aabe4](https://github.com/vuejs/vuex/commit/12aabe4cc470916d40691097dcb95badb8212f5c)) + +### Features + +* **types:** adding logger type for logger plugin ([#1853](https://github.com/vuejs/vuex/issues/1853)) ([cb3198d](https://github.com/vuejs/vuex/commit/cb3198d5998bdb11ef05dfa5ef98d5c5fa873089)) +* **build:** enable named esm module import on node.js >= 14 ([#1872](https://github.com/vuejs/vuex/issues/1872)) ([acddab2](https://github.com/vuejs/vuex/commit/acddab20769d1bb6125f2da78ac47561c682fc98)) + ## [3.5.1](https://github.com/vuejs/vuex/compare/v3.5.0...v3.5.1) (2020-06-29) diff --git a/README.md b/README.md index b8f23c95e..d8371a587 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,21 @@ -# Vuex [![Build Status](https://circleci.com/gh/vuejs/vuex/tree/dev.png?style=shield)](https://circleci.com/gh/vuejs/vuex) +# Vuex -> Centralized State Management for Vue.js. +[![npm](https://img.shields.io/npm/v/vuex.svg)](https://npmjs.com/package/vuex) +[![ci status](https://circleci.com/gh/vuejs/vuex/tree/dev.png?style=shield)](https://circleci.com/gh/vuejs/vuex) -

- -

+--- -- [What is Vuex?](https://vuex.vuejs.org/) -- [Full Documentation](http://vuex.vuejs.org/) +:fire: **HEADS UP!** You're currently looking at Vuex 3 branch. If you're looking for Vuex 4, [please check out `4.0` branch](https://github.com/vuejs/vuex/tree/4.0). + +--- + +Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It also integrates with Vue's official [devtools extension](https://github.com/vuejs/vue-devtools) to provide advanced features such as zero-config time-travel debugging and state snapshot export / import. + +Learn more about Vuex at "[What is Vuex?](https://vuex.vuejs.org/)", or get started by looking into [full documentation](http://vuex.vuejs.org/). + +## Documentation + +To check out docs, visit [vuex.vuejs.org](https://vuex.vuejs.org/). ## Examples @@ -19,11 +27,27 @@ Running the examples: -``` bash +```bash $ npm install $ npm run dev # serve examples at localhost:8080 ``` +## Questions + +For questions and support please use the [Discord chat server](https://chat.vuejs.org) or [the official forum](http://forum.vuejs.org). The issue list of this repo is **exclusively** for bug reports and feature requests. + +## Issues + +Please make sure to read the [Issue Reporting Checklist](https://github.com/vuejs/vuex/blob/dev/.github/contributing.md#issue-reporting-guidelines) before opening an issue. Issues not conforming to the guidelines may be closed immediately. + +## Changelog + +Detailed changes for each release are documented in the [release notes](https://github.com/vuejs/vuex/releases). + +## Stay In Touch + +For latest releases and announcements, follow on Twitter: [@vuejs](https://twitter.com/vuejs). + ## Contribution Please make sure to read the [Contributing Guide](https://github.com/vuejs/vuex/blob/dev/.github/contributing.md) before making a pull request. @@ -31,3 +55,5 @@ Please make sure to read the [Contributing Guide](https://github.com/vuejs/vuex/ ## License [MIT](http://opensource.org/licenses/MIT) + +Copyright (c) 2015-present Evan You diff --git a/dist/logger.d.ts b/dist/logger.d.ts deleted file mode 100644 index 8ee43089c..000000000 --- a/dist/logger.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Types for the logger plugin. This file must be put alongside the bundled -// JavaScript file of the logger. - -import { Payload, Plugin } from "../types/index"; - -export interface LoggerOption { - collapsed?: boolean; - filter?:

(mutation: P, stateBefore: S, stateAfter: S) => boolean; - transformer?: (state: S) => any; - mutationTransformer?:

(mutation: P) => any; - actionFilter?:

(action: P, state: S) => boolean; - actionTransformer?:

(action: P) => any; - logMutations?: boolean; - logActions?: boolean; -} - -export default function createLogger(option?: LoggerOption): Plugin; diff --git a/dist/logger.js b/dist/logger.js index 827af8d89..0ccaf4193 100644 --- a/dist/logger.js +++ b/dist/logger.js @@ -1,12 +1,12 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.Vuex = factory()); + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Vuex = factory()); }(this, (function () { 'use strict'; /** diff --git a/dist/vuex.cjs.js b/dist/vuex.cjs.js deleted file mode 100644 index d8309f229..000000000 --- a/dist/vuex.cjs.js +++ /dev/null @@ -1,1043 +0,0 @@ -/*! - * vuex v4.0.0-beta.2 - * (c) 2020 Evan You - * @license MIT - */ -'use strict'; - -var vue = require('vue'); - -var storeKey = 'store'; - -function useStore (key) { - if ( key === void 0 ) key = null; - - return vue.inject(key !== null ? key : storeKey) -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.hasChild = function hasChild (key) { - return key in this._children -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - if ((process.env.NODE_ENV !== 'production')) { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) -}; - -function update (path, targetModule, newModule) { - if ((process.env.NODE_ENV !== 'production')) { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -function createStore (options) { - return new Store(options) -} - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store state, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreState(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : /* Vue.config.devtools */ true; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -Store.prototype.install = function install (app, injectKey) { - app.provide(injectKey || storeKey, this); - app.config.globalProperties.$store = this; -}; - -prototypeAccessors$1.state.get = function () { - return this._state.data -}; - -prototypeAccessors$1.state.set = function (v) { - if ((process.env.NODE_ENV !== 'production')) { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - (process.env.NODE_ENV !== 'production') && - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return new Promise(function (resolve, reject) { - result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - resolve(res); - }, function (error) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.error; }) - .forEach(function (sub) { return sub.error(action, this$1.state, error); }); - } catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn("[vuex] error in error action subscribers: "); - console.error(e); - } - } - reject(error); - }); - }) -}; - -Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) -}; - -Store.prototype.watch = function watch$1 (getter, cb, options) { - var this$1 = this; - - if ((process.env.NODE_ENV !== 'production')) { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return vue.watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options)) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._state.data = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - if ((process.env.NODE_ENV !== 'production')) { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreState(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - if ((process.env.NODE_ENV !== 'production')) { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - delete parentState[path[path.length - 1]]; - }); - resetStore(this); -}; - -Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - if ((process.env.NODE_ENV !== 'production')) { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset state - resetStoreState(store, state, hot); -} - -function resetStoreState (store, state, hot) { - var oldState = store._state; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computedObj = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computedObj[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return vue.computed(function () { return computedObj[key](); }).value; }, - enumerable: true // for local getters - }); - }); - - store._state = vue.reactive({ - data: state - }); - - // enable strict mode for new state - if (store.strict) { - enableStrictMode(store); - } - - if (oldState) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldState.data = null; - }); - } - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && (process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - if ((process.env.NODE_ENV !== 'production')) { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - parentState[moduleName] = module.state; - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ((process.env.NODE_ENV !== 'production') && !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ((process.env.NODE_ENV !== 'production') && !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by state update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - vue.watch(function () { return store._state.data; }, function () { - if ((process.env.NODE_ENV !== 'production')) { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, flush: 'sync' }); -} - -function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - if ((process.env.NODE_ENV !== 'production')) { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if ((process.env.NODE_ENV !== 'production') && !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if ((process.env.NODE_ENV !== 'production') && !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index_cjs = { - version: '4.0.0-beta.2', - createStore: createStore, - Store: Store, - useStore: useStore, - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -module.exports = index_cjs; diff --git a/dist/vuex.common.js b/dist/vuex.common.js index 6d7873024..8d1c52192 100644 --- a/dist/vuex.common.js +++ b/dist/vuex.common.js @@ -1,6 +1,6 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ 'use strict'; @@ -288,7 +288,11 @@ ModuleCollection.prototype.isRegistered = function isRegistered (path) { var parent = this.get(path.slice(0, -1)); var key = path[path.length - 1]; - return parent.hasChild(key) + if (parent) { + return parent.hasChild(key) + } + + return false }; function update (path, targetModule, newModule) { @@ -963,7 +967,7 @@ var mapState = normalizeNamespace(function (namespace, states) { /** * Reduce the code which written in Vue.js for committing the mutation * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. + * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. * @return {Object} */ var mapMutations = normalizeNamespace(function (namespace, mutations) { @@ -1228,7 +1232,7 @@ function pad (num, maxLength) { var index_cjs = { Store: Store, install: install, - version: '3.5.1', + version: '3.6.2', mapState: mapState, mapMutations: mapMutations, mapGetters: mapGetters, diff --git a/dist/vuex.esm-browser.js b/dist/vuex.esm-browser.js deleted file mode 100644 index f2aa2fcc0..000000000 --- a/dist/vuex.esm-browser.js +++ /dev/null @@ -1,1042 +0,0 @@ -/*! - * vuex v4.0.0-beta.2 - * (c) 2020 Evan You - * @license MIT - */ -import { inject, watch, reactive, computed } from 'vue'; - -var storeKey = 'store'; - -function useStore (key) { - if ( key === void 0 ) key = null; - - return inject(key !== null ? key : storeKey) -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.hasChild = function hasChild (key) { - return key in this._children -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) -}; - -function update (path, targetModule, newModule) { - { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -function createStore (options) { - return new Store(options) -} - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store state, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreState(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : /* Vue.config.devtools */ true; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -Store.prototype.install = function install (app, injectKey) { - app.provide(injectKey || storeKey, this); - app.config.globalProperties.$store = this; -}; - -prototypeAccessors$1.state.get = function () { - return this._state.data -}; - -prototypeAccessors$1.state.set = function (v) { - { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return new Promise(function (resolve, reject) { - result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - resolve(res); - }, function (error) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.error; }) - .forEach(function (sub) { return sub.error(action, this$1.state, error); }); - } catch (e) { - { - console.warn("[vuex] error in error action subscribers: "); - console.error(e); - } - } - reject(error); - }); - }) -}; - -Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) -}; - -Store.prototype.watch = function watch$1 (getter, cb, options) { - var this$1 = this; - - { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options)) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._state.data = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreState(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - delete parentState[path[path.length - 1]]; - }); - resetStore(this); -}; - -Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset state - resetStoreState(store, state, hot); -} - -function resetStoreState (store, state, hot) { - var oldState = store._state; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computedObj = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computedObj[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return computed(function () { return computedObj[key](); }).value; }, - enumerable: true // for local getters - }); - }); - - store._state = reactive({ - data: state - }); - - // enable strict mode for new state - if (store.strict) { - enableStrictMode(store); - } - - if (oldState) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldState.data = null; - }); - } - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && true) { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - parentState[moduleName] = module.state; - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ( !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ( !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by state update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - watch(function () { return store._state.data; }, function () { - { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, flush: 'sync' }); -} - -function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if ( !isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if ( !isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if ( !isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if ( !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if ( !isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if ( !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index = { - version: '4.0.0-beta.2', - createStore: createStore, - Store: Store, - useStore: useStore, - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -export default index; -export { Store, createNamespacedHelpers, createStore, mapActions, mapGetters, mapMutations, mapState, useStore }; diff --git a/dist/vuex.esm-browser.prod.js b/dist/vuex.esm-browser.prod.js deleted file mode 100644 index c31475182..000000000 --- a/dist/vuex.esm-browser.prod.js +++ /dev/null @@ -1,895 +0,0 @@ -/*! - * vuex v4.0.0-beta.2 - * (c) 2020 Evan You - * @license MIT - */ -import { inject, watch, reactive, computed } from 'vue'; - -var storeKey = 'store'; - -function useStore (key) { - if ( key === void 0 ) key = null; - - return inject(key !== null ? key : storeKey) -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.hasChild = function hasChild (key) { - return key in this._children -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) -}; - -function update (path, targetModule, newModule) { - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -function createStore (options) { - return new Store(options) -} - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store state, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreState(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : /* Vue.config.devtools */ true; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -Store.prototype.install = function install (app, injectKey) { - app.provide(injectKey || storeKey, this); - app.config.globalProperties.$store = this; -}; - -prototypeAccessors$1.state.get = function () { - return this._state.data -}; - -prototypeAccessors$1.state.set = function (v) { -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return new Promise(function (resolve, reject) { - result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - } - resolve(res); - }, function (error) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.error; }) - .forEach(function (sub) { return sub.error(action, this$1.state, error); }); - } catch (e) { - } - reject(error); - }); - }) -}; - -Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) -}; - -Store.prototype.watch = function watch$1 (getter, cb, options) { - var this$1 = this; - return watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options)) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._state.data = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreState(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - delete parentState[path[path.length - 1]]; - }); - resetStore(this); -}; - -Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - return this._modules.isRegistered(path) -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset state - resetStoreState(store, state, hot); -} - -function resetStoreState (store, state, hot) { - var oldState = store._state; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computedObj = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computedObj[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return computed(function () { return computedObj[key](); }).value; }, - enumerable: true // for local getters - }); - }); - - store._state = reactive({ - data: state - }); - - // enable strict mode for new state - if (store.strict) { - enableStrictMode(store); - } - - if (oldState) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldState.data = null; - }); - } - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && false) { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - parentState[moduleName] = module.state; - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by state update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - watch(function () { return store._state.data; }, function () { - }, { deep: true, flush: 'sync' }); -} - -function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - return { type: type, payload: payload, options: options } -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - return module -} - -var index = { - version: '4.0.0-beta.2', - createStore: createStore, - Store: Store, - useStore: useStore, - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -export default index; -export { Store, createNamespacedHelpers, createStore, mapActions, mapGetters, mapMutations, mapState, useStore }; diff --git a/dist/vuex.esm-bundler.js b/dist/vuex.esm-bundler.js deleted file mode 100644 index 9a60ed2ee..000000000 --- a/dist/vuex.esm-bundler.js +++ /dev/null @@ -1,1042 +0,0 @@ -/*! - * vuex v4.0.0-beta.2 - * (c) 2020 Evan You - * @license MIT - */ -import { inject, watch, reactive, computed } from 'vue'; - -var storeKey = 'store'; - -function useStore (key) { - if ( key === void 0 ) key = null; - - return inject(key !== null ? key : storeKey) -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.hasChild = function hasChild (key) { - return key in this._children -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - if ((process.env.NODE_ENV !== 'production')) { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) -}; - -function update (path, targetModule, newModule) { - if ((process.env.NODE_ENV !== 'production')) { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -function createStore (options) { - return new Store(options) -} - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store state, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreState(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : /* Vue.config.devtools */ true; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -Store.prototype.install = function install (app, injectKey) { - app.provide(injectKey || storeKey, this); - app.config.globalProperties.$store = this; -}; - -prototypeAccessors$1.state.get = function () { - return this._state.data -}; - -prototypeAccessors$1.state.set = function (v) { - if ((process.env.NODE_ENV !== 'production')) { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - (process.env.NODE_ENV !== 'production') && - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return new Promise(function (resolve, reject) { - result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - resolve(res); - }, function (error) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.error; }) - .forEach(function (sub) { return sub.error(action, this$1.state, error); }); - } catch (e) { - if ((process.env.NODE_ENV !== 'production')) { - console.warn("[vuex] error in error action subscribers: "); - console.error(e); - } - } - reject(error); - }); - }) -}; - -Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) -}; - -Store.prototype.watch = function watch$1 (getter, cb, options) { - var this$1 = this; - - if ((process.env.NODE_ENV !== 'production')) { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options)) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._state.data = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - if ((process.env.NODE_ENV !== 'production')) { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreState(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - if ((process.env.NODE_ENV !== 'production')) { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - delete parentState[path[path.length - 1]]; - }); - resetStore(this); -}; - -Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - if ((process.env.NODE_ENV !== 'production')) { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset state - resetStoreState(store, state, hot); -} - -function resetStoreState (store, state, hot) { - var oldState = store._state; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computedObj = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computedObj[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return computed(function () { return computedObj[key](); }).value; }, - enumerable: true // for local getters - }); - }); - - store._state = reactive({ - data: state - }); - - // enable strict mode for new state - if (store.strict) { - enableStrictMode(store); - } - - if (oldState) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldState.data = null; - }); - } - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && (process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - if ((process.env.NODE_ENV !== 'production')) { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - parentState[moduleName] = module.state; - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ((process.env.NODE_ENV !== 'production') && !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ((process.env.NODE_ENV !== 'production') && !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by state update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - if ((process.env.NODE_ENV !== 'production')) { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - watch(function () { return store._state.data; }, function () { - if ((process.env.NODE_ENV !== 'production')) { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, flush: 'sync' }); -} - -function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - if ((process.env.NODE_ENV !== 'production')) { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if ((process.env.NODE_ENV !== 'production') && !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if ((process.env.NODE_ENV !== 'production') && !isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if ((process.env.NODE_ENV !== 'production') && !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index = { - version: '4.0.0-beta.2', - createStore: createStore, - Store: Store, - useStore: useStore, - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -export default index; -export { Store, createNamespacedHelpers, createStore, mapActions, mapGetters, mapMutations, mapState, useStore }; diff --git a/dist/vuex.esm.browser.js b/dist/vuex.esm.browser.js index 6628e2d19..927d4c504 100644 --- a/dist/vuex.esm.browser.js +++ b/dist/vuex.esm.browser.js @@ -1,6 +1,6 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ function applyMixin (Vue) { @@ -278,7 +278,11 @@ class ModuleCollection { const parent = this.get(path.slice(0, -1)); const key = path[path.length - 1]; - return parent.hasChild(key) + if (parent) { + return parent.hasChild(key) + } + + return false } } @@ -934,7 +938,7 @@ const mapState = normalizeNamespace((namespace, states) => { /** * Reduce the code which written in Vue.js for committing the mutation * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. + * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. * @return {Object} */ const mapMutations = normalizeNamespace((namespace, mutations) => { @@ -1183,7 +1187,7 @@ function pad (num, maxLength) { var index = { Store, install, - version: '3.5.1', + version: '3.6.2', mapState, mapMutations, mapGetters, diff --git a/dist/vuex.esm.browser.min.js b/dist/vuex.esm.browser.min.js index b0a5b4354..277efe5bf 100644 --- a/dist/vuex.esm.browser.min.js +++ b/dist/vuex.esm.browser.min.js @@ -1,6 +1,6 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ -const t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,s=[]){if(null===t||"object"!=typeof t)return t;const o=(i=e=>e.original===t,s.filter(i)[0]);var i;if(o)return o.copy;const n=Array.isArray(t)?[]:{};return s.push({original:t,copy:n}),Object.keys(t).forEach(o=>{n[o]=e(t[o],s)}),n}function s(t,e){Object.keys(t).forEach(s=>e(t[s],s))}function o(t){return null!==t&&"object"==typeof t}class i{constructor(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;const s=t.state;this.state=("function"==typeof s?s():s)||{}}get namespaced(){return!!this._rawModule.namespaced}addChild(t,e){this._children[t]=e}removeChild(t){delete this._children[t]}getChild(t){return this._children[t]}hasChild(t){return t in this._children}update(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)}forEachChild(t){s(this._children,t)}forEachGetter(t){this._rawModule.getters&&s(this._rawModule.getters,t)}forEachAction(t){this._rawModule.actions&&s(this._rawModule.actions,t)}forEachMutation(t){this._rawModule.mutations&&s(this._rawModule.mutations,t)}}class n{constructor(t){this.register([],t,!1)}get(t){return t.reduce((t,e)=>t.getChild(e),this.root)}getNamespace(t){let e=this.root;return t.reduce((t,s)=>(e=e.getChild(s),t+(e.namespaced?s+"/":"")),"")}update(t){!function t(e,s,o){if(s.update(o),o.modules)for(const i in o.modules){if(!s.getChild(i))return;t(e.concat(i),s.getChild(i),o.modules[i])}}([],this.root,t)}register(t,e,o=!0){const n=new i(e,o);if(0===t.length)this.root=n;else{this.get(t.slice(0,-1)).addChild(t[t.length-1],n)}e.modules&&s(e.modules,(e,s)=>{this.register(t.concat(s),e,o)})}unregister(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1],o=e.getChild(s);o&&o.runtime&&e.removeChild(s)}isRegistered(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1];return e.hasChild(s)}}let r;class c{constructor(e={}){!r&&"undefined"!=typeof window&&window.Vue&&f(window.Vue);const{plugins:s=[],strict:o=!1}=e;this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new n(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new r,this._makeLocalGettersCache=Object.create(null);const i=this,{dispatch:c,commit:a}=this;this.dispatch=function(t,e){return c.call(i,t,e)},this.commit=function(t,e,s){return a.call(i,t,e,s)},this.strict=o;const u=this._modules.root.state;h(this,u,[],this._modules.root),l(this,u),s.forEach(t=>t(this)),(void 0!==e.devtools?e.devtools:r.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",t=>{e.replaceState(t)}),e.subscribe((e,s)=>{t.emit("vuex:mutation",e,s)},{prepend:!0}),e.subscribeAction((e,s)=>{t.emit("vuex:action",e,s)},{prepend:!0}))}(this)}get state(){return this._vm._data.$$state}set state(t){}commit(t,e,s){const{type:o,payload:i,options:n}=p(t,e,s),r={type:o,payload:i},c=this._mutations[o];c&&(this._withCommit(()=>{c.forEach((function(t){t(i)}))}),this._subscribers.slice().forEach(t=>t(r,this.state)))}dispatch(t,e){const{type:s,payload:o}=p(t,e),i={type:s,payload:o},n=this._actions[s];if(!n)return;try{this._actionSubscribers.slice().filter(t=>t.before).forEach(t=>t.before(i,this.state))}catch(t){}const r=n.length>1?Promise.all(n.map(t=>t(o))):n[0](o);return new Promise((t,e)=>{r.then(e=>{try{this._actionSubscribers.filter(t=>t.after).forEach(t=>t.after(i,this.state))}catch(t){}t(e)},t=>{try{this._actionSubscribers.filter(t=>t.error).forEach(e=>e.error(i,this.state,t))}catch(t){}e(t)})})}subscribe(t,e){return a(t,this._subscribers,e)}subscribeAction(t,e){return a("function"==typeof t?{before:t}:t,this._actionSubscribers,e)}watch(t,e,s){return this._watcherVM.$watch(()=>t(this.state,this.getters),e,s)}replaceState(t){this._withCommit(()=>{this._vm._data.$$state=t})}registerModule(t,e,s={}){"string"==typeof t&&(t=[t]),this._modules.register(t,e),h(this,this.state,t,this._modules.get(t),s.preserveState),l(this,this.state)}unregisterModule(t){"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit(()=>{const e=d(this.state,t.slice(0,-1));r.delete(e,t[t.length-1])}),u(this)}hasModule(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)}hotUpdate(t){this._modules.update(t),u(this,!0)}_withCommit(t){const e=this._committing;this._committing=!0,t(),this._committing=e}}function a(t,e,s){return e.indexOf(t)<0&&(s&&s.prepend?e.unshift(t):e.push(t)),()=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)}}function u(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);const s=t.state;h(t,s,[],t._modules.root,!0),l(t,s,e)}function l(t,e,o){const i=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);const n=t._wrappedGetters,c={};s(n,(e,s)=>{c[s]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,s,{get:()=>t._vm[s],enumerable:!0})});const a=r.config.silent;r.config.silent=!0,t._vm=new r({data:{$$state:e},computed:c}),r.config.silent=a,t.strict&&function(t){t._vm.$watch((function(){return this._data.$$state}),()=>{},{deep:!0,sync:!0})}(t),i&&(o&&t._withCommit(()=>{i._data.$$state=null}),r.nextTick(()=>i.$destroy()))}function h(t,e,s,o,i){const n=!s.length,c=t._modules.getNamespace(s);if(o.namespaced&&(t._modulesNamespaceMap[c],t._modulesNamespaceMap[c]=o),!n&&!i){const i=d(e,s.slice(0,-1)),n=s[s.length-1];t._withCommit(()=>{r.set(i,n,o.state)})}const a=o.context=function(t,e,s){const o=""===e,i={dispatch:o?t.dispatch:(s,o,i)=>{const n=p(s,o,i),{payload:r,options:c}=n;let{type:a}=n;return c&&c.root||(a=e+a),t.dispatch(a,r)},commit:o?t.commit:(s,o,i)=>{const n=p(s,o,i),{payload:r,options:c}=n;let{type:a}=n;c&&c.root||(a=e+a),t.commit(a,r,c)}};return Object.defineProperties(i,{getters:{get:o?()=>t.getters:()=>function(t,e){if(!t._makeLocalGettersCache[e]){const s={},o=e.length;Object.keys(t.getters).forEach(i=>{if(i.slice(0,o)!==e)return;const n=i.slice(o);Object.defineProperty(s,n,{get:()=>t.getters[i],enumerable:!0})}),t._makeLocalGettersCache[e]=s}return t._makeLocalGettersCache[e]}(t,e)},state:{get:()=>d(t.state,s)}}),i}(t,c,s);o.forEachMutation((e,s)=>{!function(t,e,s,o){(t._mutations[e]||(t._mutations[e]=[])).push((function(e){s.call(t,o.state,e)}))}(t,c+s,e,a)}),o.forEachAction((e,s)=>{const o=e.root?s:c+s,i=e.handler||e;!function(t,e,s,o){(t._actions[e]||(t._actions[e]=[])).push((function(e){let i=s.call(t,{dispatch:o.dispatch,commit:o.commit,getters:o.getters,state:o.state,rootGetters:t.getters,rootState:t.state},e);var n;return(n=i)&&"function"==typeof n.then||(i=Promise.resolve(i)),t._devtoolHook?i.catch(e=>{throw t._devtoolHook.emit("vuex:error",e),e}):i}))}(t,o,i,a)}),o.forEachGetter((e,s)=>{!function(t,e,s,o){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return s(o.state,o.getters,t.state,t.getters)}}(t,c+s,e,a)}),o.forEachChild((o,n)=>{h(t,e,s.concat(n),o,i)})}function d(t,e){return e.reduce((t,e)=>t[e],t)}function p(t,e,s){return o(t)&&t.type&&(s=e,e=t,t=t.type),{type:t,payload:e,options:s}}function f(t){r&&t===r||(r=t,function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:e});else{const s=t.prototype._init;t.prototype._init=function(t={}){t.init=t.init?[e].concat(t.init):e,s.call(this,t)}}function e(){const t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(r))}const m=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{s[e]=function(){let e=this.$store.state,s=this.$store.getters;if(t){const o=$(this.$store,"mapState",t);if(!o)return;e=o.context.state,s=o.context.getters}return"function"==typeof o?o.call(this,e,s):e[o]},s[e].vuex=!0}),s}),g=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{s[e]=function(...e){let s=this.$store.commit;if(t){const e=$(this.$store,"mapMutations",t);if(!e)return;s=e.context.commit}return"function"==typeof o?o.apply(this,[s].concat(e)):s.apply(this.$store,[o].concat(e))}}),s}),_=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{o=t+o,s[e]=function(){if(!t||$(this.$store,"mapGetters",t))return this.$store.getters[o]},s[e].vuex=!0}),s}),y=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{s[e]=function(...e){let s=this.$store.dispatch;if(t){const e=$(this.$store,"mapActions",t);if(!e)return;s=e.context.dispatch}return"function"==typeof o?o.apply(this,[s].concat(e)):s.apply(this.$store,[o].concat(e))}}),s}),b=t=>({mapState:m.bind(null,t),mapGetters:_.bind(null,t),mapMutations:g.bind(null,t),mapActions:y.bind(null,t)});function w(t){return function(t){return Array.isArray(t)||o(t)}(t)?Array.isArray(t)?t.map(t=>({key:t,val:t})):Object.keys(t).map(e=>({key:e,val:t[e]})):[]}function v(t){return(e,s)=>("string"!=typeof e?(s=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,s))}function $(t,e,s){return t._modulesNamespaceMap[s]}function M({collapsed:t=!0,filter:s=((t,e,s)=>!0),transformer:o=(t=>t),mutationTransformer:i=(t=>t),actionFilter:n=((t,e)=>!0),actionTransformer:r=(t=>t),logMutations:c=!0,logActions:a=!0,logger:u=console}={}){return l=>{let h=e(l.state);void 0!==u&&(c&&l.subscribe((n,r)=>{const c=e(r);if(s(n,h,c)){const e=O(),s=i(n),r=`mutation ${n.type}${e}`;C(u,r,t),u.log("%c prev state","color: #9E9E9E; font-weight: bold",o(h)),u.log("%c mutation","color: #03A9F4; font-weight: bold",s),u.log("%c next state","color: #4CAF50; font-weight: bold",o(c)),E(u)}h=c}),a&&l.subscribeAction((e,s)=>{if(n(e,s)){const s=O(),o=r(e),i=`action ${e.type}${s}`;C(u,i,t),u.log("%c action","color: #03A9F4; font-weight: bold",o),E(u)}}))}}function C(t,e,s){const o=s?t.groupCollapsed:t.group;try{o.call(t,e)}catch(s){t.log(e)}}function E(t){try{t.groupEnd()}catch(e){t.log("—— log end ——")}}function O(){const t=new Date;return` @ ${j(t.getHours(),2)}:${j(t.getMinutes(),2)}:${j(t.getSeconds(),2)}.${j(t.getMilliseconds(),3)}`}function j(t,e){return s="0",o=e-t.toString().length,new Array(o+1).join(s)+t;var s,o}var A={Store:c,install:f,version:"3.5.1",mapState:m,mapMutations:g,mapGetters:_,mapActions:y,createNamespacedHelpers:b,createLogger:M};export default A;export{c as Store,M as createLogger,b as createNamespacedHelpers,f as install,y as mapActions,_ as mapGetters,g as mapMutations,m as mapState}; +const t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,s=[]){if(null===t||"object"!=typeof t)return t;const o=(i=e=>e.original===t,s.filter(i)[0]);var i;if(o)return o.copy;const n=Array.isArray(t)?[]:{};return s.push({original:t,copy:n}),Object.keys(t).forEach(o=>{n[o]=e(t[o],s)}),n}function s(t,e){Object.keys(t).forEach(s=>e(t[s],s))}function o(t){return null!==t&&"object"==typeof t}class i{constructor(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;const s=t.state;this.state=("function"==typeof s?s():s)||{}}get namespaced(){return!!this._rawModule.namespaced}addChild(t,e){this._children[t]=e}removeChild(t){delete this._children[t]}getChild(t){return this._children[t]}hasChild(t){return t in this._children}update(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)}forEachChild(t){s(this._children,t)}forEachGetter(t){this._rawModule.getters&&s(this._rawModule.getters,t)}forEachAction(t){this._rawModule.actions&&s(this._rawModule.actions,t)}forEachMutation(t){this._rawModule.mutations&&s(this._rawModule.mutations,t)}}class n{constructor(t){this.register([],t,!1)}get(t){return t.reduce((t,e)=>t.getChild(e),this.root)}getNamespace(t){let e=this.root;return t.reduce((t,s)=>(e=e.getChild(s),t+(e.namespaced?s+"/":"")),"")}update(t){!function t(e,s,o){if(s.update(o),o.modules)for(const i in o.modules){if(!s.getChild(i))return;t(e.concat(i),s.getChild(i),o.modules[i])}}([],this.root,t)}register(t,e,o=!0){const n=new i(e,o);if(0===t.length)this.root=n;else{this.get(t.slice(0,-1)).addChild(t[t.length-1],n)}e.modules&&s(e.modules,(e,s)=>{this.register(t.concat(s),e,o)})}unregister(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1],o=e.getChild(s);o&&o.runtime&&e.removeChild(s)}isRegistered(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1];return!!e&&e.hasChild(s)}}let r;class c{constructor(e={}){!r&&"undefined"!=typeof window&&window.Vue&&f(window.Vue);const{plugins:s=[],strict:o=!1}=e;this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new n(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new r,this._makeLocalGettersCache=Object.create(null);const i=this,{dispatch:c,commit:a}=this;this.dispatch=function(t,e){return c.call(i,t,e)},this.commit=function(t,e,s){return a.call(i,t,e,s)},this.strict=o;const u=this._modules.root.state;h(this,u,[],this._modules.root),l(this,u),s.forEach(t=>t(this));(void 0!==e.devtools?e.devtools:r.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",t=>{e.replaceState(t)}),e.subscribe((e,s)=>{t.emit("vuex:mutation",e,s)},{prepend:!0}),e.subscribeAction((e,s)=>{t.emit("vuex:action",e,s)},{prepend:!0}))}(this)}get state(){return this._vm._data.$$state}set state(t){}commit(t,e,s){const{type:o,payload:i,options:n}=p(t,e,s),r={type:o,payload:i},c=this._mutations[o];c&&(this._withCommit(()=>{c.forEach((function(t){t(i)}))}),this._subscribers.slice().forEach(t=>t(r,this.state)))}dispatch(t,e){const{type:s,payload:o}=p(t,e),i={type:s,payload:o},n=this._actions[s];if(!n)return;try{this._actionSubscribers.slice().filter(t=>t.before).forEach(t=>t.before(i,this.state))}catch(t){}const r=n.length>1?Promise.all(n.map(t=>t(o))):n[0](o);return new Promise((t,e)=>{r.then(e=>{try{this._actionSubscribers.filter(t=>t.after).forEach(t=>t.after(i,this.state))}catch(t){}t(e)},t=>{try{this._actionSubscribers.filter(t=>t.error).forEach(e=>e.error(i,this.state,t))}catch(t){}e(t)})})}subscribe(t,e){return a(t,this._subscribers,e)}subscribeAction(t,e){return a("function"==typeof t?{before:t}:t,this._actionSubscribers,e)}watch(t,e,s){return this._watcherVM.$watch(()=>t(this.state,this.getters),e,s)}replaceState(t){this._withCommit(()=>{this._vm._data.$$state=t})}registerModule(t,e,s={}){"string"==typeof t&&(t=[t]),this._modules.register(t,e),h(this,this.state,t,this._modules.get(t),s.preserveState),l(this,this.state)}unregisterModule(t){"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit(()=>{const e=d(this.state,t.slice(0,-1));r.delete(e,t[t.length-1])}),u(this)}hasModule(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)}hotUpdate(t){this._modules.update(t),u(this,!0)}_withCommit(t){const e=this._committing;this._committing=!0,t(),this._committing=e}}function a(t,e,s){return e.indexOf(t)<0&&(s&&s.prepend?e.unshift(t):e.push(t)),()=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)}}function u(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);const s=t.state;h(t,s,[],t._modules.root,!0),l(t,s,e)}function l(t,e,o){const i=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);const n=t._wrappedGetters,c={};s(n,(e,s)=>{c[s]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,s,{get:()=>t._vm[s],enumerable:!0})});const a=r.config.silent;r.config.silent=!0,t._vm=new r({data:{$$state:e},computed:c}),r.config.silent=a,t.strict&&function(t){t._vm.$watch((function(){return this._data.$$state}),()=>{},{deep:!0,sync:!0})}(t),i&&(o&&t._withCommit(()=>{i._data.$$state=null}),r.nextTick(()=>i.$destroy()))}function h(t,e,s,o,i){const n=!s.length,c=t._modules.getNamespace(s);if(o.namespaced&&(t._modulesNamespaceMap[c],t._modulesNamespaceMap[c]=o),!n&&!i){const i=d(e,s.slice(0,-1)),n=s[s.length-1];t._withCommit(()=>{r.set(i,n,o.state)})}const a=o.context=function(t,e,s){const o=""===e,i={dispatch:o?t.dispatch:(s,o,i)=>{const n=p(s,o,i),{payload:r,options:c}=n;let{type:a}=n;return c&&c.root||(a=e+a),t.dispatch(a,r)},commit:o?t.commit:(s,o,i)=>{const n=p(s,o,i),{payload:r,options:c}=n;let{type:a}=n;c&&c.root||(a=e+a),t.commit(a,r,c)}};return Object.defineProperties(i,{getters:{get:o?()=>t.getters:()=>function(t,e){if(!t._makeLocalGettersCache[e]){const s={},o=e.length;Object.keys(t.getters).forEach(i=>{if(i.slice(0,o)!==e)return;const n=i.slice(o);Object.defineProperty(s,n,{get:()=>t.getters[i],enumerable:!0})}),t._makeLocalGettersCache[e]=s}return t._makeLocalGettersCache[e]}(t,e)},state:{get:()=>d(t.state,s)}}),i}(t,c,s);o.forEachMutation((e,s)=>{!function(t,e,s,o){(t._mutations[e]||(t._mutations[e]=[])).push((function(e){s.call(t,o.state,e)}))}(t,c+s,e,a)}),o.forEachAction((e,s)=>{const o=e.root?s:c+s,i=e.handler||e;!function(t,e,s,o){(t._actions[e]||(t._actions[e]=[])).push((function(e){let i=s.call(t,{dispatch:o.dispatch,commit:o.commit,getters:o.getters,state:o.state,rootGetters:t.getters,rootState:t.state},e);var n;return(n=i)&&"function"==typeof n.then||(i=Promise.resolve(i)),t._devtoolHook?i.catch(e=>{throw t._devtoolHook.emit("vuex:error",e),e}):i}))}(t,o,i,a)}),o.forEachGetter((e,s)=>{!function(t,e,s,o){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return s(o.state,o.getters,t.state,t.getters)}}(t,c+s,e,a)}),o.forEachChild((o,n)=>{h(t,e,s.concat(n),o,i)})}function d(t,e){return e.reduce((t,e)=>t[e],t)}function p(t,e,s){return o(t)&&t.type&&(s=e,e=t,t=t.type),{type:t,payload:e,options:s}}function f(t){r&&t===r||(r=t,function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:e});else{const s=t.prototype._init;t.prototype._init=function(t={}){t.init=t.init?[e].concat(t.init):e,s.call(this,t)}}function e(){const t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(r))}const m=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{s[e]=function(){let e=this.$store.state,s=this.$store.getters;if(t){const o=$(this.$store,"mapState",t);if(!o)return;e=o.context.state,s=o.context.getters}return"function"==typeof o?o.call(this,e,s):e[o]},s[e].vuex=!0}),s}),g=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{s[e]=function(...e){let s=this.$store.commit;if(t){const e=$(this.$store,"mapMutations",t);if(!e)return;s=e.context.commit}return"function"==typeof o?o.apply(this,[s].concat(e)):s.apply(this.$store,[o].concat(e))}}),s}),_=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{o=t+o,s[e]=function(){if(!t||$(this.$store,"mapGetters",t))return this.$store.getters[o]},s[e].vuex=!0}),s}),y=v((t,e)=>{const s={};return w(e).forEach(({key:e,val:o})=>{s[e]=function(...e){let s=this.$store.dispatch;if(t){const e=$(this.$store,"mapActions",t);if(!e)return;s=e.context.dispatch}return"function"==typeof o?o.apply(this,[s].concat(e)):s.apply(this.$store,[o].concat(e))}}),s}),b=t=>({mapState:m.bind(null,t),mapGetters:_.bind(null,t),mapMutations:g.bind(null,t),mapActions:y.bind(null,t)});function w(t){return function(t){return Array.isArray(t)||o(t)}(t)?Array.isArray(t)?t.map(t=>({key:t,val:t})):Object.keys(t).map(e=>({key:e,val:t[e]})):[]}function v(t){return(e,s)=>("string"!=typeof e?(s=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,s))}function $(t,e,s){return t._modulesNamespaceMap[s]}function M({collapsed:t=!0,filter:s=((t,e,s)=>!0),transformer:o=(t=>t),mutationTransformer:i=(t=>t),actionFilter:n=((t,e)=>!0),actionTransformer:r=(t=>t),logMutations:c=!0,logActions:a=!0,logger:u=console}={}){return l=>{let h=e(l.state);void 0!==u&&(c&&l.subscribe((n,r)=>{const c=e(r);if(s(n,h,c)){const e=O(),s=i(n),r=`mutation ${n.type}${e}`;C(u,r,t),u.log("%c prev state","color: #9E9E9E; font-weight: bold",o(h)),u.log("%c mutation","color: #03A9F4; font-weight: bold",s),u.log("%c next state","color: #4CAF50; font-weight: bold",o(c)),E(u)}h=c}),a&&l.subscribeAction((e,s)=>{if(n(e,s)){const s=O(),o=r(e),i=`action ${e.type}${s}`;C(u,i,t),u.log("%c action","color: #03A9F4; font-weight: bold",o),E(u)}}))}}function C(t,e,s){const o=s?t.groupCollapsed:t.group;try{o.call(t,e)}catch(s){t.log(e)}}function E(t){try{t.groupEnd()}catch(e){t.log("—— log end ——")}}function O(){const t=new Date;return` @ ${j(t.getHours(),2)}:${j(t.getMinutes(),2)}:${j(t.getSeconds(),2)}.${j(t.getMilliseconds(),3)}`}function j(t,e){return s="0",o=e-t.toString().length,new Array(o+1).join(s)+t;var s,o}var A={Store:c,install:f,version:"3.6.2",mapState:m,mapMutations:g,mapGetters:_,mapActions:y,createNamespacedHelpers:b,createLogger:M};export default A;export{c as Store,M as createLogger,b as createNamespacedHelpers,f as install,y as mapActions,_ as mapGetters,g as mapMutations,m as mapState}; diff --git a/dist/vuex.esm.js b/dist/vuex.esm.js index 0a59ceb24..9466ff0ab 100644 --- a/dist/vuex.esm.js +++ b/dist/vuex.esm.js @@ -1,6 +1,6 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ function applyMixin (Vue) { @@ -286,7 +286,11 @@ ModuleCollection.prototype.isRegistered = function isRegistered (path) { var parent = this.get(path.slice(0, -1)); var key = path[path.length - 1]; - return parent.hasChild(key) + if (parent) { + return parent.hasChild(key) + } + + return false }; function update (path, targetModule, newModule) { @@ -961,7 +965,7 @@ var mapState = normalizeNamespace(function (namespace, states) { /** * Reduce the code which written in Vue.js for committing the mutation * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. + * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. * @return {Object} */ var mapMutations = normalizeNamespace(function (namespace, mutations) { @@ -1226,7 +1230,7 @@ function pad (num, maxLength) { var index = { Store: Store, install: install, - version: '3.5.1', + version: '3.6.2', mapState: mapState, mapMutations: mapMutations, mapGetters: mapGetters, diff --git a/dist/vuex.global.js b/dist/vuex.global.js deleted file mode 100644 index f43a3d7b4..000000000 --- a/dist/vuex.global.js +++ /dev/null @@ -1,1044 +0,0 @@ -/*! - * vuex v4.0.0-beta.2 - * (c) 2020 Evan You - * @license MIT - */ -var Vuex = (function (vue) { - 'use strict'; - - var storeKey = 'store'; - - function useStore (key) { - if ( key === void 0 ) key = null; - - return vue.inject(key !== null ? key : storeKey) - } - - var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; - var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - - function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); - } - - /** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - - /** - * forEach for object - */ - function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); - } - - function isObject (obj) { - return obj !== null && typeof obj === 'object' - } - - function isPromise (val) { - return val && typeof val.then === 'function' - } - - function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } - } - - function partial (fn, arg) { - return function () { - return fn(arg) - } - } - - // Base data struct for store's module, package with some attribute and method - var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; - }; - - var prototypeAccessors = { namespaced: { configurable: true } }; - - prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced - }; - - Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; - }; - - Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; - }; - - Module.prototype.getChild = function getChild (key) { - return this._children[key] - }; - - Module.prototype.hasChild = function hasChild (key) { - return key in this._children - }; - - Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } - }; - - Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); - }; - - Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } - }; - - Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } - }; - - Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } - }; - - Object.defineProperties( Module.prototype, prototypeAccessors ); - - var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); - }; - - ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) - }; - - ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') - }; - - ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); - }; - - ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } - }; - - ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); - }; - - ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) - }; - - function update (path, targetModule, newModule) { - { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } - } - - var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' - }; - - var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' - }; - - var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert - }; - - function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); - } - - function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf - } - - function createStore (options) { - return new Store(options) - } - - var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store state, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreState(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : /* Vue.config.devtools */ true; - if (useDevtools) { - devtoolPlugin(this); - } - }; - - var prototypeAccessors$1 = { state: { configurable: true } }; - - Store.prototype.install = function install (app, injectKey) { - app.provide(injectKey || storeKey, this); - app.config.globalProperties.$store = this; - }; - - prototypeAccessors$1.state.get = function () { - return this._state.data - }; - - prototypeAccessors$1.state.set = function (v) { - { - assert(false, "use store.replaceState() to explicit replace store state."); - } - }; - - Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } - }; - - Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return new Promise(function (resolve, reject) { - result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - resolve(res); - }, function (error) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.error; }) - .forEach(function (sub) { return sub.error(action, this$1.state, error); }); - } catch (e) { - { - console.warn("[vuex] error in error action subscribers: "); - console.error(e); - } - } - reject(error); - }); - }) - }; - - Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) - }; - - Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) - }; - - Store.prototype.watch = function watch$1 (getter, cb, options) { - var this$1 = this; - - { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return vue.watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options)) - }; - - Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._state.data = state; - }); - }; - - Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreState(this, this.state); - }; - - Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - delete parentState[path[path.length - 1]]; - }); - resetStore(this); - }; - - Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) - }; - - Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); - }; - - Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; - }; - - Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - - function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } - } - - function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset state - resetStoreState(store, state, hot); - } - - function resetStoreState (store, state, hot) { - var oldState = store._state; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computedObj = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computedObj[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return vue.computed(function () { return computedObj[key](); }).value; }, - enumerable: true // for local getters - }); - }); - - store._state = vue.reactive({ - data: state - }); - - // enable strict mode for new state - if (store.strict) { - enableStrictMode(store); - } - - if (oldState) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldState.data = null; - }); - } - } - } - - function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && true) { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - parentState[moduleName] = module.state; - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); - } - - /** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ - function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ( !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if ( !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by state update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local - } - - function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] - } - - function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); - } - - function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); - } - - function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; - } - - function enableStrictMode (store) { - vue.watch(function () { return store._state.data; }, function () { - { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, flush: 'sync' }); - } - - function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) - } - - function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } - } - - /** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it. - * @param {Object} - */ - var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if ( !isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ - var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if ( !isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ - var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if ( !isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if ( !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function. - * @return {Object} - */ - var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if ( !isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res - }); - - /** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ - var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) - }); }; - - /** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ - function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) - } - - /** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ - function isValidMap (map) { - return Array.isArray(map) || isObject(map) - } - - /** - * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map. - * @param {Function} fn - * @return {Function} - */ - function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } - } - - /** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ - function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if ( !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module - } - - var index_cjs = { - version: '4.0.0-beta.2', - createStore: createStore, - Store: Store, - useStore: useStore, - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers - }; - - return index_cjs; - -}(Vue)); diff --git a/dist/vuex.global.prod.js b/dist/vuex.global.prod.js deleted file mode 100644 index 0a7fd9315..000000000 --- a/dist/vuex.global.prod.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! - * vuex v4.0.0-beta.2 - * (c) 2020 Evan You - * @license MIT - */ -var Vuex=function(t){"use strict";var e=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function n(t,e){Object.keys(t).forEach((function(n){return e(t[n],n)}))}function r(t){return null!==t&&"object"==typeof t}function o(t,e){if(!t)throw new Error("[vuex] "+e)}var i=function(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;var n=t.state;this.state=("function"==typeof n?n():n)||{}},s={namespaced:{configurable:!0}};s.namespaced.get=function(){return!!this._rawModule.namespaced},i.prototype.addChild=function(t,e){this._children[t]=e},i.prototype.removeChild=function(t){delete this._children[t]},i.prototype.getChild=function(t){return this._children[t]},i.prototype.hasChild=function(t){return t in this._children},i.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},i.prototype.forEachChild=function(t){n(this._children,t)},i.prototype.forEachGetter=function(t){this._rawModule.getters&&n(this._rawModule.getters,t)},i.prototype.forEachAction=function(t){this._rawModule.actions&&n(this._rawModule.actions,t)},i.prototype.forEachMutation=function(t){this._rawModule.mutations&&n(this._rawModule.mutations,t)},Object.defineProperties(i.prototype,s);var a=function(t){this.register([],t,!1)};a.prototype.get=function(t){return t.reduce((function(t,e){return t.getChild(e)}),this.root)},a.prototype.getNamespace=function(t){var e=this.root;return t.reduce((function(t,n){return t+((e=e.getChild(n)).namespaced?n+"/":"")}),"")},a.prototype.update=function(t){!function t(e,n,r){if(n.update(r),r.modules)for(var o in r.modules){if(!n.getChild(o))return;t(e.concat(o),n.getChild(o),r.modules[o])}}([],this.root,t)},a.prototype.register=function(t,e,r){var o=this;void 0===r&&(r=!0);var s=new i(e,r);0===t.length?this.root=s:this.get(t.slice(0,-1)).addChild(t[t.length-1],s);e.modules&&n(e.modules,(function(e,n){o.register(t.concat(n),e,r)}))},a.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];e.getChild(n).runtime&&e.removeChild(n)},a.prototype.isRegistered=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];return e.hasChild(n)};var c=function t(n){var r=this;void 0===n&&(n={}),"production"!==process.env.NODE_ENV&&(o("undefined"!=typeof Promise,"vuex requires a Promise polyfill in this browser."),o(this instanceof t,"store must be called with the new operator."));var i=n.plugins;void 0===i&&(i=[]);var s=n.strict;void 0===s&&(s=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new a(n),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._makeLocalGettersCache=Object.create(null);var c=this,u=this.dispatch,f=this.commit;this.dispatch=function(t,e){return u.call(c,t,e)},this.commit=function(t,e,n){return f.call(c,t,e,n)},this.strict=s;var h=this._modules.root.state;l(this,h,[],this._modules.root),p(this,h),i.forEach((function(t){return t(r)})),(void 0===n.devtools||n.devtools)&&function(t){e&&(t._devtoolHook=e,e.emit("vuex:init",t),e.on("vuex:travel-to-state",(function(e){t.replaceState(e)})),t.subscribe((function(t,n){e.emit("vuex:mutation",t,n)}),{prepend:!0}),t.subscribeAction((function(t,n){e.emit("vuex:action",t,n)}),{prepend:!0}))}(this)},u={state:{configurable:!0}};function f(t,e,n){return e.indexOf(t)<0&&(n&&n.prepend?e.unshift(t):e.push(t)),function(){var n=e.indexOf(t);n>-1&&e.splice(n,1)}}function h(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);var n=t.state;l(t,n,[],t._modules.root,!0),p(t,n,e)}function p(e,r,o){var i=e._state;e.getters={},e._makeLocalGettersCache=Object.create(null);var s=e._wrappedGetters,a={};n(s,(function(n,r){a[r]=function(t,e){return function(){return t(e)}}(n,e),Object.defineProperty(e.getters,r,{get:function(){return t.computed((function(){return a[r]()})).value},enumerable:!0})})),e._state=t.reactive({data:r}),e.strict&&function(e){t.watch((function(){return e._state.data}),(function(){}),{deep:!0,flush:"sync"})}(e),i&&o&&e._withCommit((function(){i.data=null}))}function l(t,e,n,r,o){var i=!n.length,s=t._modules.getNamespace(n);if(r.namespaced&&(t._modulesNamespaceMap[s],t._modulesNamespaceMap[s]=r),!i&&!o){var a=d(e,n.slice(0,-1)),c=n[n.length-1];t._withCommit((function(){a[c]=r.state}))}var u=r.context=function(t,e,n){var r=""===e,o={dispatch:r?t.dispatch:function(n,r,o){var i=m(n,r,o),s=i.payload,a=i.options,c=i.type;return a&&a.root||(c=e+c),t.dispatch(c,s)},commit:r?t.commit:function(n,r,o){var i=m(n,r,o),s=i.payload,a=i.options,c=i.type;a&&a.root||(c=e+c),t.commit(c,s,a)}};return Object.defineProperties(o,{getters:{get:r?function(){return t.getters}:function(){return function(t,e){if(!t._makeLocalGettersCache[e]){var n={},r=e.length;Object.keys(t.getters).forEach((function(o){if(o.slice(0,r)===e){var i=o.slice(r);Object.defineProperty(n,i,{get:function(){return t.getters[o]},enumerable:!0})}})),t._makeLocalGettersCache[e]=n}return t._makeLocalGettersCache[e]}(t,e)}},state:{get:function(){return d(t.state,n)}}}),o}(t,s,n);r.forEachMutation((function(e,n){!function(t,e,n,r){(t._mutations[e]||(t._mutations[e]=[])).push((function(e){n.call(t,r.state,e)}))}(t,s+n,e,u)})),r.forEachAction((function(e,n){var r=e.root?n:s+n,o=e.handler||e;!function(t,e,n,r){(t._actions[e]||(t._actions[e]=[])).push((function(e){var o,i=n.call(t,{dispatch:r.dispatch,commit:r.commit,getters:r.getters,state:r.state,rootGetters:t.getters,rootState:t.state},e);return(o=i)&&"function"==typeof o.then||(i=Promise.resolve(i)),t._devtoolHook?i.catch((function(e){throw t._devtoolHook.emit("vuex:error",e),e})):i}))}(t,r,o,u)})),r.forEachGetter((function(e,n){!function(t,e,n,r){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return n(r.state,r.getters,t.state,t.getters)}}(t,s+n,e,u)})),r.forEachChild((function(r,i){l(t,e,n.concat(i),r,o)}))}function d(t,e){return e.reduce((function(t,e){return t[e]}),t)}function m(t,e,n){return r(t)&&t.type&&(n=e,e=t,t=t.type),{type:t,payload:e,options:n}}c.prototype.install=function(t,e){t.provide(e||"store",this),t.config.globalProperties.$store=this},u.state.get=function(){return this._state.data},u.state.set=function(t){},c.prototype.commit=function(t,e,n){var r=this,o=m(t,e,n),i=o.type,s=o.payload,a={type:i,payload:s},c=this._mutations[i];c&&(this._withCommit((function(){c.forEach((function(t){t(s)}))})),this._subscribers.slice().forEach((function(t){return t(a,r.state)})))},c.prototype.dispatch=function(t,e){var n=this,r=m(t,e),o=r.type,i=r.payload,s={type:o,payload:i},a=this._actions[o];if(a){try{this._actionSubscribers.slice().filter((function(t){return t.before})).forEach((function(t){return t.before(s,n.state)}))}catch(t){}var c=a.length>1?Promise.all(a.map((function(t){return t(i)}))):a[0](i);return new Promise((function(t,e){c.then((function(e){try{n._actionSubscribers.filter((function(t){return t.after})).forEach((function(t){return t.after(s,n.state)}))}catch(t){}t(e)}),(function(t){try{n._actionSubscribers.filter((function(t){return t.error})).forEach((function(e){return e.error(s,n.state,t)}))}catch(t){}e(t)}))}))}},c.prototype.subscribe=function(t,e){return f(t,this._subscribers,e)},c.prototype.subscribeAction=function(t,e){return f("function"==typeof t?{before:t}:t,this._actionSubscribers,e)},c.prototype.watch=function(e,n,r){var o=this;return t.watch((function(){return e(o.state,o.getters)}),n,Object.assign({},r))},c.prototype.replaceState=function(t){var e=this;this._withCommit((function(){e._state.data=t}))},c.prototype.registerModule=function(t,e,n){void 0===n&&(n={}),"string"==typeof t&&(t=[t]),this._modules.register(t,e),l(this,this.state,t,this._modules.get(t),n.preserveState),p(this,this.state)},c.prototype.unregisterModule=function(t){var e=this;"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit((function(){delete d(e.state,t.slice(0,-1))[t[t.length-1]]})),h(this)},c.prototype.hasModule=function(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)},c.prototype.hotUpdate=function(t){this._modules.update(t),h(this,!0)},c.prototype._withCommit=function(t){var e=this._committing;this._committing=!0,t(),this._committing=e},Object.defineProperties(c.prototype,u);var v=w((function(t,e){var n={};return b(e).forEach((function(e){var r=e.key,o=e.val;n[r]=function(){var e=this.$store.state,n=this.$store.getters;if(t){var r=O(this.$store,"mapState",t);if(!r)return;e=r.context.state,n=r.context.getters}return"function"==typeof o?o.call(this,e,n):e[o]},n[r].vuex=!0})),n})),_=w((function(t,e){var n={};return b(e).forEach((function(e){var r=e.key,o=e.val;n[r]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var r=this.$store.commit;if(t){var i=O(this.$store,"mapMutations",t);if(!i)return;r=i.context.commit}return"function"==typeof o?o.apply(this,[r].concat(e)):r.apply(this.$store,[o].concat(e))}})),n})),y=w((function(t,e){var n={};return b(e).forEach((function(e){var r=e.key,o=e.val;o=t+o,n[r]=function(){if(!t||O(this.$store,"mapGetters",t))return this.$store.getters[o]},n[r].vuex=!0})),n})),g=w((function(t,e){var n={};return b(e).forEach((function(e){var r=e.key,o=e.val;n[r]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var r=this.$store.dispatch;if(t){var i=O(this.$store,"mapActions",t);if(!i)return;r=i.context.dispatch}return"function"==typeof o?o.apply(this,[r].concat(e)):r.apply(this.$store,[o].concat(e))}})),n}));function b(t){return function(t){return Array.isArray(t)||r(t)}(t)?Array.isArray(t)?t.map((function(t){return{key:t,val:t}})):Object.keys(t).map((function(e){return{key:e,val:t[e]}})):[]}function w(t){return function(e,n){return"string"!=typeof e?(n=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,n)}}function O(t,e,n){return t._modulesNamespaceMap[n]}return{version:"4.0.0-beta.2",createStore:function(t){return new c(t)},Store:c,useStore:function(e){return void 0===e&&(e=null),t.inject(null!==e?e:"store")},mapState:v,mapMutations:_,mapGetters:y,mapActions:g,createNamespacedHelpers:function(t){return{mapState:v.bind(null,t),mapGetters:y.bind(null,t),mapMutations:_.bind(null,t),mapActions:g.bind(null,t)}}}}(Vue); diff --git a/dist/vuex.js b/dist/vuex.js index 98f199439..291300427 100644 --- a/dist/vuex.js +++ b/dist/vuex.js @@ -1,12 +1,12 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.Vuex = factory()); + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Vuex = factory()); }(this, (function () { 'use strict'; function applyMixin (Vue) { @@ -292,7 +292,11 @@ var parent = this.get(path.slice(0, -1)); var key = path[path.length - 1]; - return parent.hasChild(key) + if (parent) { + return parent.hasChild(key) + } + + return false }; function update (path, targetModule, newModule) { @@ -967,7 +971,7 @@ /** * Reduce the code which written in Vue.js for committing the mutation * @param {String} [namespace] - Module's namespace - * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. + * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function. * @return {Object} */ var mapMutations = normalizeNamespace(function (namespace, mutations) { @@ -1232,7 +1236,7 @@ var index_cjs = { Store: Store, install: install, - version: '3.5.1', + version: '3.6.2', mapState: mapState, mapMutations: mapMutations, mapGetters: mapGetters, diff --git a/dist/vuex.min.js b/dist/vuex.min.js index 57c88636c..3871c68cd 100644 --- a/dist/vuex.min.js +++ b/dist/vuex.min.js @@ -1,6 +1,6 @@ /*! - * vuex v3.5.1 - * (c) 2020 Evan You + * vuex v3.6.2 + * (c) 2021 Evan You * @license MIT */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Vuex=e()}(this,(function(){"use strict";var t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,n){if(void 0===n&&(n=[]),null===t||"object"!=typeof t)return t;var o,r=(o=function(e){return e.original===t},n.filter(o)[0]);if(r)return r.copy;var i=Array.isArray(t)?[]:{};return n.push({original:t,copy:i}),Object.keys(t).forEach((function(o){i[o]=e(t[o],n)})),i}function n(t,e){Object.keys(t).forEach((function(n){return e(t[n],n)}))}function o(t){return null!==t&&"object"==typeof t}var r=function(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;var n=t.state;this.state=("function"==typeof n?n():n)||{}},i={namespaced:{configurable:!0}};i.namespaced.get=function(){return!!this._rawModule.namespaced},r.prototype.addChild=function(t,e){this._children[t]=e},r.prototype.removeChild=function(t){delete this._children[t]},r.prototype.getChild=function(t){return this._children[t]},r.prototype.hasChild=function(t){return t in this._children},r.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},r.prototype.forEachChild=function(t){n(this._children,t)},r.prototype.forEachGetter=function(t){this._rawModule.getters&&n(this._rawModule.getters,t)},r.prototype.forEachAction=function(t){this._rawModule.actions&&n(this._rawModule.actions,t)},r.prototype.forEachMutation=function(t){this._rawModule.mutations&&n(this._rawModule.mutations,t)},Object.defineProperties(r.prototype,i);var c,a=function(t){this.register([],t,!1)};a.prototype.get=function(t){return t.reduce((function(t,e){return t.getChild(e)}),this.root)},a.prototype.getNamespace=function(t){var e=this.root;return t.reduce((function(t,n){return t+((e=e.getChild(n)).namespaced?n+"/":"")}),"")},a.prototype.update=function(t){!function t(e,n,o){if(n.update(o),o.modules)for(var r in o.modules){if(!n.getChild(r))return;t(e.concat(r),n.getChild(r),o.modules[r])}}([],this.root,t)},a.prototype.register=function(t,e,o){var i=this;void 0===o&&(o=!0);var c=new r(e,o);0===t.length?this.root=c:this.get(t.slice(0,-1)).addChild(t[t.length-1],c);e.modules&&n(e.modules,(function(e,n){i.register(t.concat(n),e,o)}))},a.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1],o=e.getChild(n);o&&o.runtime&&e.removeChild(n)},a.prototype.isRegistered=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];return e.hasChild(n)};var s=function(e){var n=this;void 0===e&&(e={}),!c&&"undefined"!=typeof window&&window.Vue&&v(window.Vue);var o=e.plugins;void 0===o&&(o=[]);var r=e.strict;void 0===r&&(r=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new a(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new c,this._makeLocalGettersCache=Object.create(null);var i=this,s=this.dispatch,u=this.commit;this.dispatch=function(t,e){return s.call(i,t,e)},this.commit=function(t,e,n){return u.call(i,t,e,n)},this.strict=r;var f=this._modules.root.state;h(this,f,[],this._modules.root),p(this,f),o.forEach((function(t){return t(n)})),(void 0!==e.devtools?e.devtools:c.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",(function(t){e.replaceState(t)})),e.subscribe((function(e,n){t.emit("vuex:mutation",e,n)}),{prepend:!0}),e.subscribeAction((function(e,n){t.emit("vuex:action",e,n)}),{prepend:!0}))}(this)},u={state:{configurable:!0}};function f(t,e,n){return e.indexOf(t)<0&&(n&&n.prepend?e.unshift(t):e.push(t)),function(){var n=e.indexOf(t);n>-1&&e.splice(n,1)}}function l(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);var n=t.state;h(t,n,[],t._modules.root,!0),p(t,n,e)}function p(t,e,o){var r=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);var i=t._wrappedGetters,a={};n(i,(function(e,n){a[n]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,n,{get:function(){return t._vm[n]},enumerable:!0})}));var s=c.config.silent;c.config.silent=!0,t._vm=new c({data:{$$state:e},computed:a}),c.config.silent=s,t.strict&&function(t){t._vm.$watch((function(){return this._data.$$state}),(function(){}),{deep:!0,sync:!0})}(t),r&&(o&&t._withCommit((function(){r._data.$$state=null})),c.nextTick((function(){return r.$destroy()})))}function h(t,e,n,o,r){var i=!n.length,a=t._modules.getNamespace(n);if(o.namespaced&&(t._modulesNamespaceMap[a],t._modulesNamespaceMap[a]=o),!i&&!r){var s=d(e,n.slice(0,-1)),u=n[n.length-1];t._withCommit((function(){c.set(s,u,o.state)}))}var f=o.context=function(t,e,n){var o=""===e,r={dispatch:o?t.dispatch:function(n,o,r){var i=m(n,o,r),c=i.payload,a=i.options,s=i.type;return a&&a.root||(s=e+s),t.dispatch(s,c)},commit:o?t.commit:function(n,o,r){var i=m(n,o,r),c=i.payload,a=i.options,s=i.type;a&&a.root||(s=e+s),t.commit(s,c,a)}};return Object.defineProperties(r,{getters:{get:o?function(){return t.getters}:function(){return function(t,e){if(!t._makeLocalGettersCache[e]){var n={},o=e.length;Object.keys(t.getters).forEach((function(r){if(r.slice(0,o)===e){var i=r.slice(o);Object.defineProperty(n,i,{get:function(){return t.getters[r]},enumerable:!0})}})),t._makeLocalGettersCache[e]=n}return t._makeLocalGettersCache[e]}(t,e)}},state:{get:function(){return d(t.state,n)}}}),r}(t,a,n);o.forEachMutation((function(e,n){!function(t,e,n,o){(t._mutations[e]||(t._mutations[e]=[])).push((function(e){n.call(t,o.state,e)}))}(t,a+n,e,f)})),o.forEachAction((function(e,n){var o=e.root?n:a+n,r=e.handler||e;!function(t,e,n,o){(t._actions[e]||(t._actions[e]=[])).push((function(e){var r,i=n.call(t,{dispatch:o.dispatch,commit:o.commit,getters:o.getters,state:o.state,rootGetters:t.getters,rootState:t.state},e);return(r=i)&&"function"==typeof r.then||(i=Promise.resolve(i)),t._devtoolHook?i.catch((function(e){throw t._devtoolHook.emit("vuex:error",e),e})):i}))}(t,o,r,f)})),o.forEachGetter((function(e,n){!function(t,e,n,o){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return n(o.state,o.getters,t.state,t.getters)}}(t,a+n,e,f)})),o.forEachChild((function(o,i){h(t,e,n.concat(i),o,r)}))}function d(t,e){return e.reduce((function(t,e){return t[e]}),t)}function m(t,e,n){return o(t)&&t.type&&(n=e,e=t,t=t.type),{type:t,payload:e,options:n}}function v(t){c&&t===c||function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:n});else{var e=t.prototype._init;t.prototype._init=function(t){void 0===t&&(t={}),t.init=t.init?[n].concat(t.init):n,e.call(this,t)}}function n(){var t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(c=t)}u.state.get=function(){return this._vm._data.$$state},u.state.set=function(t){},s.prototype.commit=function(t,e,n){var o=this,r=m(t,e,n),i=r.type,c=r.payload,a={type:i,payload:c},s=this._mutations[i];s&&(this._withCommit((function(){s.forEach((function(t){t(c)}))})),this._subscribers.slice().forEach((function(t){return t(a,o.state)})))},s.prototype.dispatch=function(t,e){var n=this,o=m(t,e),r=o.type,i=o.payload,c={type:r,payload:i},a=this._actions[r];if(a){try{this._actionSubscribers.slice().filter((function(t){return t.before})).forEach((function(t){return t.before(c,n.state)}))}catch(t){}var s=a.length>1?Promise.all(a.map((function(t){return t(i)}))):a[0](i);return new Promise((function(t,e){s.then((function(e){try{n._actionSubscribers.filter((function(t){return t.after})).forEach((function(t){return t.after(c,n.state)}))}catch(t){}t(e)}),(function(t){try{n._actionSubscribers.filter((function(t){return t.error})).forEach((function(e){return e.error(c,n.state,t)}))}catch(t){}e(t)}))}))}},s.prototype.subscribe=function(t,e){return f(t,this._subscribers,e)},s.prototype.subscribeAction=function(t,e){return f("function"==typeof t?{before:t}:t,this._actionSubscribers,e)},s.prototype.watch=function(t,e,n){var o=this;return this._watcherVM.$watch((function(){return t(o.state,o.getters)}),e,n)},s.prototype.replaceState=function(t){var e=this;this._withCommit((function(){e._vm._data.$$state=t}))},s.prototype.registerModule=function(t,e,n){void 0===n&&(n={}),"string"==typeof t&&(t=[t]),this._modules.register(t,e),h(this,this.state,t,this._modules.get(t),n.preserveState),p(this,this.state)},s.prototype.unregisterModule=function(t){var e=this;"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit((function(){var n=d(e.state,t.slice(0,-1));c.delete(n,t[t.length-1])})),l(this)},s.prototype.hasModule=function(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)},s.prototype.hotUpdate=function(t){this._modules.update(t),l(this,!0)},s.prototype._withCommit=function(t){var e=this._committing;this._committing=!0,t(),this._committing=e},Object.defineProperties(s.prototype,u);var g=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;n[o]=function(){var e=this.$store.state,n=this.$store.getters;if(t){var o=$(this.$store,"mapState",t);if(!o)return;e=o.context.state,n=o.context.getters}return"function"==typeof r?r.call(this,e,n):e[r]},n[o].vuex=!0})),n})),y=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.commit;if(t){var i=$(this.$store,"mapMutations",t);if(!i)return;o=i.context.commit}return"function"==typeof r?r.apply(this,[o].concat(e)):o.apply(this.$store,[r].concat(e))}})),n})),_=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;r=t+r,n[o]=function(){if(!t||$(this.$store,"mapGetters",t))return this.$store.getters[r]},n[o].vuex=!0})),n})),b=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.dispatch;if(t){var i=$(this.$store,"mapActions",t);if(!i)return;o=i.context.dispatch}return"function"==typeof r?r.apply(this,[o].concat(e)):o.apply(this.$store,[r].concat(e))}})),n}));function w(t){return function(t){return Array.isArray(t)||o(t)}(t)?Array.isArray(t)?t.map((function(t){return{key:t,val:t}})):Object.keys(t).map((function(e){return{key:e,val:t[e]}})):[]}function M(t){return function(e,n){return"string"!=typeof e?(n=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,n)}}function $(t,e,n){return t._modulesNamespaceMap[n]}function C(t,e,n){var o=n?t.groupCollapsed:t.group;try{o.call(t,e)}catch(n){t.log(e)}}function E(t){try{t.groupEnd()}catch(e){t.log("—— log end ——")}}function O(){var t=new Date;return" @ "+j(t.getHours(),2)+":"+j(t.getMinutes(),2)+":"+j(t.getSeconds(),2)+"."+j(t.getMilliseconds(),3)}function j(t,e){return n="0",o=e-t.toString().length,new Array(o+1).join(n)+t;var n,o}return{Store:s,install:v,version:"3.5.1",mapState:g,mapMutations:y,mapGetters:_,mapActions:b,createNamespacedHelpers:function(t){return{mapState:g.bind(null,t),mapGetters:_.bind(null,t),mapMutations:y.bind(null,t),mapActions:b.bind(null,t)}},createLogger:function(t){void 0===t&&(t={});var n=t.collapsed;void 0===n&&(n=!0);var o=t.filter;void 0===o&&(o=function(t,e,n){return!0});var r=t.transformer;void 0===r&&(r=function(t){return t});var i=t.mutationTransformer;void 0===i&&(i=function(t){return t});var c=t.actionFilter;void 0===c&&(c=function(t,e){return!0});var a=t.actionTransformer;void 0===a&&(a=function(t){return t});var s=t.logMutations;void 0===s&&(s=!0);var u=t.logActions;void 0===u&&(u=!0);var f=t.logger;return void 0===f&&(f=console),function(t){var l=e(t.state);void 0!==f&&(s&&t.subscribe((function(t,c){var a=e(c);if(o(t,l,a)){var s=O(),u=i(t),p="mutation "+t.type+s;C(f,p,n),f.log("%c prev state","color: #9E9E9E; font-weight: bold",r(l)),f.log("%c mutation","color: #03A9F4; font-weight: bold",u),f.log("%c next state","color: #4CAF50; font-weight: bold",r(a)),E(f)}l=a})),u&&t.subscribeAction((function(t,e){if(c(t,e)){var o=O(),r=a(t),i="action "+t.type+o;C(f,i,n),f.log("%c action","color: #03A9F4; font-weight: bold",r),E(f)}})))}}}})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Vuex=e()}(this,(function(){"use strict";var t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,n){if(void 0===n&&(n=[]),null===t||"object"!=typeof t)return t;var o,r=(o=function(e){return e.original===t},n.filter(o)[0]);if(r)return r.copy;var i=Array.isArray(t)?[]:{};return n.push({original:t,copy:i}),Object.keys(t).forEach((function(o){i[o]=e(t[o],n)})),i}function n(t,e){Object.keys(t).forEach((function(n){return e(t[n],n)}))}function o(t){return null!==t&&"object"==typeof t}var r=function(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;var n=t.state;this.state=("function"==typeof n?n():n)||{}},i={namespaced:{configurable:!0}};i.namespaced.get=function(){return!!this._rawModule.namespaced},r.prototype.addChild=function(t,e){this._children[t]=e},r.prototype.removeChild=function(t){delete this._children[t]},r.prototype.getChild=function(t){return this._children[t]},r.prototype.hasChild=function(t){return t in this._children},r.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},r.prototype.forEachChild=function(t){n(this._children,t)},r.prototype.forEachGetter=function(t){this._rawModule.getters&&n(this._rawModule.getters,t)},r.prototype.forEachAction=function(t){this._rawModule.actions&&n(this._rawModule.actions,t)},r.prototype.forEachMutation=function(t){this._rawModule.mutations&&n(this._rawModule.mutations,t)},Object.defineProperties(r.prototype,i);var c,a=function(t){this.register([],t,!1)};a.prototype.get=function(t){return t.reduce((function(t,e){return t.getChild(e)}),this.root)},a.prototype.getNamespace=function(t){var e=this.root;return t.reduce((function(t,n){return t+((e=e.getChild(n)).namespaced?n+"/":"")}),"")},a.prototype.update=function(t){!function t(e,n,o){if(n.update(o),o.modules)for(var r in o.modules){if(!n.getChild(r))return;t(e.concat(r),n.getChild(r),o.modules[r])}}([],this.root,t)},a.prototype.register=function(t,e,o){var i=this;void 0===o&&(o=!0);var c=new r(e,o);0===t.length?this.root=c:this.get(t.slice(0,-1)).addChild(t[t.length-1],c);e.modules&&n(e.modules,(function(e,n){i.register(t.concat(n),e,o)}))},a.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1],o=e.getChild(n);o&&o.runtime&&e.removeChild(n)},a.prototype.isRegistered=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];return!!e&&e.hasChild(n)};var s=function(e){var n=this;void 0===e&&(e={}),!c&&"undefined"!=typeof window&&window.Vue&&v(window.Vue);var o=e.plugins;void 0===o&&(o=[]);var r=e.strict;void 0===r&&(r=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new a(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new c,this._makeLocalGettersCache=Object.create(null);var i=this,s=this.dispatch,u=this.commit;this.dispatch=function(t,e){return s.call(i,t,e)},this.commit=function(t,e,n){return u.call(i,t,e,n)},this.strict=r;var f=this._modules.root.state;p(this,f,[],this._modules.root),h(this,f),o.forEach((function(t){return t(n)})),(void 0!==e.devtools?e.devtools:c.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",(function(t){e.replaceState(t)})),e.subscribe((function(e,n){t.emit("vuex:mutation",e,n)}),{prepend:!0}),e.subscribeAction((function(e,n){t.emit("vuex:action",e,n)}),{prepend:!0}))}(this)},u={state:{configurable:!0}};function f(t,e,n){return e.indexOf(t)<0&&(n&&n.prepend?e.unshift(t):e.push(t)),function(){var n=e.indexOf(t);n>-1&&e.splice(n,1)}}function l(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);var n=t.state;p(t,n,[],t._modules.root,!0),h(t,n,e)}function h(t,e,o){var r=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);var i=t._wrappedGetters,a={};n(i,(function(e,n){a[n]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,n,{get:function(){return t._vm[n]},enumerable:!0})}));var s=c.config.silent;c.config.silent=!0,t._vm=new c({data:{$$state:e},computed:a}),c.config.silent=s,t.strict&&function(t){t._vm.$watch((function(){return this._data.$$state}),(function(){}),{deep:!0,sync:!0})}(t),r&&(o&&t._withCommit((function(){r._data.$$state=null})),c.nextTick((function(){return r.$destroy()})))}function p(t,e,n,o,r){var i=!n.length,a=t._modules.getNamespace(n);if(o.namespaced&&(t._modulesNamespaceMap[a],t._modulesNamespaceMap[a]=o),!i&&!r){var s=d(e,n.slice(0,-1)),u=n[n.length-1];t._withCommit((function(){c.set(s,u,o.state)}))}var f=o.context=function(t,e,n){var o=""===e,r={dispatch:o?t.dispatch:function(n,o,r){var i=m(n,o,r),c=i.payload,a=i.options,s=i.type;return a&&a.root||(s=e+s),t.dispatch(s,c)},commit:o?t.commit:function(n,o,r){var i=m(n,o,r),c=i.payload,a=i.options,s=i.type;a&&a.root||(s=e+s),t.commit(s,c,a)}};return Object.defineProperties(r,{getters:{get:o?function(){return t.getters}:function(){return function(t,e){if(!t._makeLocalGettersCache[e]){var n={},o=e.length;Object.keys(t.getters).forEach((function(r){if(r.slice(0,o)===e){var i=r.slice(o);Object.defineProperty(n,i,{get:function(){return t.getters[r]},enumerable:!0})}})),t._makeLocalGettersCache[e]=n}return t._makeLocalGettersCache[e]}(t,e)}},state:{get:function(){return d(t.state,n)}}}),r}(t,a,n);o.forEachMutation((function(e,n){!function(t,e,n,o){(t._mutations[e]||(t._mutations[e]=[])).push((function(e){n.call(t,o.state,e)}))}(t,a+n,e,f)})),o.forEachAction((function(e,n){var o=e.root?n:a+n,r=e.handler||e;!function(t,e,n,o){(t._actions[e]||(t._actions[e]=[])).push((function(e){var r,i=n.call(t,{dispatch:o.dispatch,commit:o.commit,getters:o.getters,state:o.state,rootGetters:t.getters,rootState:t.state},e);return(r=i)&&"function"==typeof r.then||(i=Promise.resolve(i)),t._devtoolHook?i.catch((function(e){throw t._devtoolHook.emit("vuex:error",e),e})):i}))}(t,o,r,f)})),o.forEachGetter((function(e,n){!function(t,e,n,o){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return n(o.state,o.getters,t.state,t.getters)}}(t,a+n,e,f)})),o.forEachChild((function(o,i){p(t,e,n.concat(i),o,r)}))}function d(t,e){return e.reduce((function(t,e){return t[e]}),t)}function m(t,e,n){return o(t)&&t.type&&(n=e,e=t,t=t.type),{type:t,payload:e,options:n}}function v(t){c&&t===c||function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:n});else{var e=t.prototype._init;t.prototype._init=function(t){void 0===t&&(t={}),t.init=t.init?[n].concat(t.init):n,e.call(this,t)}}function n(){var t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(c=t)}u.state.get=function(){return this._vm._data.$$state},u.state.set=function(t){},s.prototype.commit=function(t,e,n){var o=this,r=m(t,e,n),i=r.type,c=r.payload,a={type:i,payload:c},s=this._mutations[i];s&&(this._withCommit((function(){s.forEach((function(t){t(c)}))})),this._subscribers.slice().forEach((function(t){return t(a,o.state)})))},s.prototype.dispatch=function(t,e){var n=this,o=m(t,e),r=o.type,i=o.payload,c={type:r,payload:i},a=this._actions[r];if(a){try{this._actionSubscribers.slice().filter((function(t){return t.before})).forEach((function(t){return t.before(c,n.state)}))}catch(t){}var s=a.length>1?Promise.all(a.map((function(t){return t(i)}))):a[0](i);return new Promise((function(t,e){s.then((function(e){try{n._actionSubscribers.filter((function(t){return t.after})).forEach((function(t){return t.after(c,n.state)}))}catch(t){}t(e)}),(function(t){try{n._actionSubscribers.filter((function(t){return t.error})).forEach((function(e){return e.error(c,n.state,t)}))}catch(t){}e(t)}))}))}},s.prototype.subscribe=function(t,e){return f(t,this._subscribers,e)},s.prototype.subscribeAction=function(t,e){return f("function"==typeof t?{before:t}:t,this._actionSubscribers,e)},s.prototype.watch=function(t,e,n){var o=this;return this._watcherVM.$watch((function(){return t(o.state,o.getters)}),e,n)},s.prototype.replaceState=function(t){var e=this;this._withCommit((function(){e._vm._data.$$state=t}))},s.prototype.registerModule=function(t,e,n){void 0===n&&(n={}),"string"==typeof t&&(t=[t]),this._modules.register(t,e),p(this,this.state,t,this._modules.get(t),n.preserveState),h(this,this.state)},s.prototype.unregisterModule=function(t){var e=this;"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit((function(){var n=d(e.state,t.slice(0,-1));c.delete(n,t[t.length-1])})),l(this)},s.prototype.hasModule=function(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)},s.prototype.hotUpdate=function(t){this._modules.update(t),l(this,!0)},s.prototype._withCommit=function(t){var e=this._committing;this._committing=!0,t(),this._committing=e},Object.defineProperties(s.prototype,u);var g=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;n[o]=function(){var e=this.$store.state,n=this.$store.getters;if(t){var o=$(this.$store,"mapState",t);if(!o)return;e=o.context.state,n=o.context.getters}return"function"==typeof r?r.call(this,e,n):e[r]},n[o].vuex=!0})),n})),y=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.commit;if(t){var i=$(this.$store,"mapMutations",t);if(!i)return;o=i.context.commit}return"function"==typeof r?r.apply(this,[o].concat(e)):o.apply(this.$store,[r].concat(e))}})),n})),_=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;r=t+r,n[o]=function(){if(!t||$(this.$store,"mapGetters",t))return this.$store.getters[r]},n[o].vuex=!0})),n})),b=M((function(t,e){var n={};return w(e).forEach((function(e){var o=e.key,r=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.dispatch;if(t){var i=$(this.$store,"mapActions",t);if(!i)return;o=i.context.dispatch}return"function"==typeof r?r.apply(this,[o].concat(e)):o.apply(this.$store,[r].concat(e))}})),n}));function w(t){return function(t){return Array.isArray(t)||o(t)}(t)?Array.isArray(t)?t.map((function(t){return{key:t,val:t}})):Object.keys(t).map((function(e){return{key:e,val:t[e]}})):[]}function M(t){return function(e,n){return"string"!=typeof e?(n=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,n)}}function $(t,e,n){return t._modulesNamespaceMap[n]}function C(t,e,n){var o=n?t.groupCollapsed:t.group;try{o.call(t,e)}catch(n){t.log(e)}}function E(t){try{t.groupEnd()}catch(e){t.log("—— log end ——")}}function O(){var t=new Date;return" @ "+j(t.getHours(),2)+":"+j(t.getMinutes(),2)+":"+j(t.getSeconds(),2)+"."+j(t.getMilliseconds(),3)}function j(t,e){return n="0",o=e-t.toString().length,new Array(o+1).join(n)+t;var n,o}return{Store:s,install:v,version:"3.6.2",mapState:g,mapMutations:y,mapGetters:_,mapActions:b,createNamespacedHelpers:function(t){return{mapState:g.bind(null,t),mapGetters:_.bind(null,t),mapMutations:y.bind(null,t),mapActions:b.bind(null,t)}},createLogger:function(t){void 0===t&&(t={});var n=t.collapsed;void 0===n&&(n=!0);var o=t.filter;void 0===o&&(o=function(t,e,n){return!0});var r=t.transformer;void 0===r&&(r=function(t){return t});var i=t.mutationTransformer;void 0===i&&(i=function(t){return t});var c=t.actionFilter;void 0===c&&(c=function(t,e){return!0});var a=t.actionTransformer;void 0===a&&(a=function(t){return t});var s=t.logMutations;void 0===s&&(s=!0);var u=t.logActions;void 0===u&&(u=!0);var f=t.logger;return void 0===f&&(f=console),function(t){var l=e(t.state);void 0!==f&&(s&&t.subscribe((function(t,c){var a=e(c);if(o(t,l,a)){var s=O(),u=i(t),h="mutation "+t.type+s;C(f,h,n),f.log("%c prev state","color: #9E9E9E; font-weight: bold",r(l)),f.log("%c mutation","color: #03A9F4; font-weight: bold",u),f.log("%c next state","color: #4CAF50; font-weight: bold",r(a)),E(f)}l=a})),u&&t.subscribeAction((function(t,e){if(c(t,e)){var o=O(),r=a(t),i="action "+t.type+o;C(f,i,n),f.log("%c action","color: #03A9F4; font-weight: bold",r),E(f)}})))}}}})); diff --git a/dist/vuex.mjs b/dist/vuex.mjs new file mode 100644 index 000000000..2140898f4 --- /dev/null +++ b/dist/vuex.mjs @@ -0,0 +1,26 @@ +import Vuex from '../dist/vuex.common.js' + +const { + Store, + install, + version, + mapState, + mapMutations, + mapGetters, + mapActions, + createNamespacedHelpers, + createLogger +} = Vuex + +export { + Vuex as default, + Store, + install, + version, + mapState, + mapMutations, + mapGetters, + mapActions, + createNamespacedHelpers, + createLogger +} diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index d1b8c92ff..f0b2a4d6f 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -59,7 +59,13 @@ module.exports = { nav: [ { text: 'Guide', link: '/guide/' }, { text: 'API Reference', link: '/api/' }, - { text: 'Release Notes', link: 'https://github.com/vuejs/vuex/releases' } + { text: 'Release Notes', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/' } + ] + } ], sidebar: [ { @@ -103,7 +109,13 @@ module.exports = { nav: [ { text: '指南', link: '/zh/guide/' }, { text: 'API 参考', link: '/zh/api/' }, - { text: '更新记录', link: 'https://github.com/vuejs/vuex/releases' } + { text: '更新记录', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/' } + ] + } ], sidebar: [ { @@ -147,7 +159,13 @@ module.exports = { nav: [ { text: 'ガイド', link: '/ja/guide/' }, { text: 'API リファレンス', link: '/ja/api/' }, - { text: 'リリースノート', link: 'https://github.com/vuejs/vuex/releases' } + { text: 'リリースノート', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/' } + ] + } ], sidebar: [ { @@ -191,7 +209,13 @@ module.exports = { nav: [ { text: 'Руководство', link: '/ru/guide/' }, { text: 'Справочник API', link: '/ru/api/' }, - { text: 'История изменений', link: 'https://github.com/vuejs/vuex/releases' } + { text: 'История изменений', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/' } + ] + } ], sidebar: [ { @@ -235,7 +259,13 @@ module.exports = { nav: [ { text: '가이드', link: '/kr/guide/' }, { text: 'API 레퍼런스', link: '/kr/api/' }, - { text: '릴리즈 노트', link: 'https://github.com/vuejs/vuex/releases' } + { text: '릴리즈 노트', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/' } + ] + } ], sidebar: [ { @@ -279,7 +309,13 @@ module.exports = { nav: [ { text: 'Guia', link: '/ptbr/guide/' }, { text: 'Referência da API', link: '/ptbr/api/' }, - { text: 'Notas da Versão', link: 'https://github.com/vuejs/vuex/releases' } + { text: 'Notas da Versão', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/ptbr/' } + ] + } ], sidebar: [ { @@ -323,7 +359,13 @@ module.exports = { nav: [ { text: 'Guide', link: '/fr/guide/' }, { text: 'API', link: '/fr/api/' }, - { text: 'Notes de version', link: 'https://github.com/vuejs/vuex/releases' } + { text: 'Notes de version', link: 'https://github.com/vuejs/vuex/releases' }, + { + text: 'v3.x', + items: [ + { text: 'v4.x', link: 'https://next.vuex.vuejs.org/' } + ] + } ], sidebar: [ { diff --git a/docs/README.md b/docs/README.md index c75bb088a..682df03f3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,9 @@ # What is Vuex? +::: tip NOTE +This is the docs for Vuex 3, which works with Vue 2. If you're looking for docs for Vuex 4, which works with Vue 3, [please check it out here](https://next.vuex.vuejs.org/). +::: + Vuex is a **state management pattern + library** for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It also integrates with Vue's official [devtools extension](https://github.com/vuejs/vue-devtools) to provide advanced features such as zero-config time-travel debugging and state snapshot export / import. diff --git a/docs/api/README.md b/docs/api/README.md index 49439f15b..7000fa469 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -168,9 +168,18 @@ const store = new Vuex.Store({ ...options }) - `watch(fn: Function, callback: Function, options?: Object): Function` - Reactively watch `fn`'s return value, and call the callback when the value changes. `fn` receives the store's state as the first argument, and getters as the second argument. Accepts an optional options object that takes the same options as [Vue's `vm.$watch` method](https://vuejs.org/v2/api/#vm-watch). + Reactively watch `fn`'s return value, and call the callback when the value changes. `fn` receives the store's state as the first argument, and getters as the second argument. The third argument accepts the same options as [Vue's `vm.$watch` method](https://vuejs.org/v2/api/#vm-watch). To stop watching, call the returned unwatch function. + + ```js + const unwatch = store.watch( + (state, getters) => state.myWatchedProperty, + (newVal, oldVal) => { + // Do something with watched + } + ) + ``` ### subscribe diff --git a/docs/guide/README.md b/docs/guide/README.md index f473a1ac2..06aa66f2c 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -16,8 +16,6 @@ We will be using ES2015 syntax for code examples for the rest of the docs. If yo After [installing](../installation.md) Vuex, let's create a store. It is pretty straightforward - just provide an initial state object, and some mutations: -### Vuex 3.x (for Vue 2) - ```js import Vue from 'vue' import Vuex from 'vuex' @@ -36,24 +34,6 @@ const store = new Vuex.Store({ }) ``` -### Vuex 4.x (for Vue 3) - -```js -import { createStore } from 'vuex' -import { createApp } from 'vue' - -const store = createStore({ - state () { - return { - count: 1 - } - } -}) - -const app = createApp({ /* your root component */ }) -app.use(store) -``` - Now, you can access the state object as `store.state`, and trigger a state change with the `store.commit` method: ```js diff --git a/docs/guide/modules.md b/docs/guide/modules.md index e09d6f8c6..e6a52f17b 100644 --- a/docs/guide/modules.md +++ b/docs/guide/modules.md @@ -85,7 +85,7 @@ const moduleA = { ## Namespacing -By default, actions, mutations and getters inside modules are still registered under the **global namespace** - this allows multiple modules to react to the same mutation/action type. +By default, actions and mutations are still registered under the **global namespace** - this allows multiple modules to react to the same action/mutation type. Getters are also registered in the global namespace by default. However, this currently has no functional purpose (it's as is to avoid breaking changes). You must be careful not to define two getters with the same name in different, non-namespaced modules, resulting in an error. If you want your modules to be more self-contained or reusable, you can mark it as namespaced with `namespaced: true`. When the module is registered, all of its getters, actions and mutations will be automatically namespaced based on the path the module is registered at. For example: diff --git a/docs/installation.md b/docs/installation.md index 75d411aaa..6e1761440 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -19,24 +19,16 @@ Include `vuex` after Vue and it will install itself automatically: ```bash npm install vuex --save - -# If using Vue 3.0 + Vuex 4.0: -npm install vuex@next --save ``` ## Yarn ```bash yarn add vuex - -# If using Vue 3.0 + Vuex 4.0: -yarn add vuex@next --save ``` When used with a module system, you must explicitly install Vuex as a plugin: -### With Vue 2 - ```js import Vue from 'vue' import Vuex from 'vuex' @@ -44,18 +36,6 @@ import Vuex from 'vuex' Vue.use(Vuex) ``` -### With Vue 3 - -```js -import { createApp } from 'vue' -import { createStore } from 'vuex' - -const app = createApp({ ... }) -const store = createStore({ ... }) - -app.use(store) -``` - You don't need to do this when using global script tags. ## Promise diff --git a/docs/ptbr/README.md b/docs/ptbr/README.md index 945ff0424..dbc9d40c6 100644 --- a/docs/ptbr/README.md +++ b/docs/ptbr/README.md @@ -1,12 +1,16 @@ # O que é Vuex? +::: tip NOTE +Esta documentação é para o Vuex 3, que funciona com Vue 2. Se você está procurando a documentação para o Vuex 4, que funciona com Vue 3, [por favor, confira aqui](https://next.vuex.vuejs.org/ptbr/). +::: + -O Vuex é um **padrão de gerenciamento de estado + biblioteca** para aplicativos Vue.js. Ele serve como um _store_ centralizado para todos os componentes em uma aplicação, com regras garantindo que o estado só possa ser mutado de forma previsível. Ele também se integra com a extensão oficial [Vue devtools](https://github.com/vuejs/vue-devtools) para fornecer recursos avançados sem configurações adicionais, como depuração viajando pelo histórico de estado (_time travel_) e exportação/importação de registros de estado em determinado momento. +O Vuex é um **padrão de gerenciamento de estado + biblioteca** para aplicações Vue.js. Ele serve como um _store_ centralizado para todos os componentes em uma aplicação, com regras garantindo que o estado só possa ser mutado de forma previsível. Ele também se integra com a extensão oficial [Vue devtools](https://github.com/vuejs/vue-devtools) para fornecer recursos avançados sem configurações adicionais, como depuração viajando pelo histórico de estado (_time travel_) e exportação/importação de registros de estado em determinado momento. ### O que é um "Padrão de Gerenciamento do Estado"? -Vamos começar com um aplicativo simples de contador Vue: +Vamos começar com uma aplicação simples de contador Vue: ``` js new Vue({ @@ -29,9 +33,9 @@ new Vue({ }) ``` -É um aplicativo independente com as seguintes partes: +É uma aplicação independente com as seguintes partes: -- O **estado** (_state_), que é a fonte da verdade que direciona nosso aplicativo; +- O **estado** (_state_), que é a fonte da verdade que direciona nossa aplicação; - A **_view_**, que é apenas um mapeamento declarativo do **estado**; - As **ações** (_actions_), que são as possíveis maneiras pelas quais o estado pode mudar em reação às interações dos usuários da **_view_**. @@ -62,6 +66,6 @@ Se você quiser aprender Vuex de um modo interativo, você pode conferir esse cu Embora o Vuex nos ajude a lidar com o gerenciamento de estado compartilhado, ele também vem com o custo de mais conceitos e códigos repetitivos. É uma escolha de prós e contras entre produtividade de curto e longo prazo -Se você nunca construiu um SPA em grande escala e for direto para o Vuex, ele pode parecer detalhado e desanimador. Isso é perfeitamente normal - se o seu aplicativo é simples, você provavelmente ficará bem sem o Vuex. Um simples [store pattern](https://br.vuejs.org/v2/guide/state-management.html#Gerenciamento-de-Estado-do-Zero) pode ser tudo que você precisa. Mas, se você está criando um SPA de médio a grande porte, é provável que tenha encontrado situações que fazem você pensar em como lidar melhor com o estado fora de seus componentes do Vue, e o Vuex será o próximo passo natural para você. Há uma boa citação de Dan Abramov, o autor do Redux: +Se você nunca construiu um SPA em grande escala e for direto para o Vuex, ele pode parecer detalhado e desanimador. Isso é perfeitamente normal - se a sua aplicação é simples, você provavelmente ficará bem sem o Vuex. Um simples [store pattern](https://br.vuejs.org/v2/guide/state-management.html#Gerenciamento-de-Estado-do-Zero) pode ser tudo que você precisa. Mas, se você está criando um SPA de médio a grande porte, é provável que tenha encontrado situações que fazem você pensar em como lidar melhor com o estado fora de seus componentes do Vue, e o Vuex será o próximo passo natural para você. Há uma boa citação de Dan Abramov, o autor do Redux: > As bibliotecas _Flux_ são como óculos: você saberá quando precisar delas. diff --git a/docs/ptbr/api/README.md b/docs/ptbr/api/README.md index 3840a5104..9d5366d89 100644 --- a/docs/ptbr/api/README.md +++ b/docs/ptbr/api/README.md @@ -71,7 +71,7 @@ const store = new Vuex.Store({ ...options }) rootGetters // todos os getters ``` - Os _getters_ registrados estão expostos em _store.getters_. + Os _getters_ registrados estão expostos em `store.getters`. [Detalhes](../guide/getters.md) @@ -95,7 +95,7 @@ const store = new Vuex.Store({ ...options }) } ``` - Cada módulo pode conter `estado` e `mutações` semelhantes às opções raiz. O estado de um módulo será anexado ao estado da raiz do _store_ usando a chave do módulo. As mutações e _getters_ de um módulo receberão apenas o estado local do módulo como o 1º argumento em vez do estado da raiz e as ações do módulo _context.state_ também apontarão para o estado local. + Cada módulo pode conter `estado` e `mutações` semelhantes às opções raiz. O estado de um módulo será anexado ao estado da raiz do _store_ usando a chave do módulo. As mutações e _getters_ de um módulo receberão apenas o estado local do módulo como o 1º argumento em vez do estado da raiz e as ações do módulo `context.state` também apontarão para o estado local. [Detalhes](../guide/modules.md) @@ -103,7 +103,7 @@ const store = new Vuex.Store({ ...options }) - type: `Array` - Um _Array_ de funções de plug-in a serem aplicadas no _store_. O plug-in simplesmente recebe o _store_ como o único argumento e pode ouvir mutações (para persistência de dados de saída, registro ou depuração) ou mutações de despacho (para dados de entrada, por exemplo, websockets ou _observables_). + Um _Array_ de funções de _plugin_ a serem aplicadas no _store_. O _plugin_ simplesmente recebe o _store_ como o único argumento e pode ouvir mutações (para persistência de dados de saída, registro ou depuração) ou mutações de despacho (para dados de entrada, por exemplo, websockets ou _observables_). [Detalhes](../guide/plugins.md) @@ -120,7 +120,7 @@ const store = new Vuex.Store({ ...options }) - type: `boolean` - Ative ou desative as ferramentas de desenvolvedor para uma determinada instância vuex. Passar _false_ à instância diz ao _store_ Vuex para não se integrar ao _devtools_. Útil para quando se tem vários _stores_ em uma _single page_. + Ative ou desative as ferramentas de desenvolvedor para uma determinada instância vuex. Passar `false` à instância diz ao _store_ Vuex para não se integrar ao _devtools_. Útil para quando se tem vários _stores_ em uma _single_ _page_. ``` js { @@ -149,14 +149,14 @@ const store = new Vuex.Store({ ...options }) - `commit(type: string, payload?: any, options?: Object)` - `commit(mutation: Object, options?: Object)` - Confirma (ou faz um _Commit_ de) uma mutação. _options_ pode ter _root: true_ que permite confirmar mutações da raiz em [módulos namespaced](../guide/modules.md#namespacing). [Detalhes](../guide/mutations.md) + Confirma (ou faz um _Commit_ de) uma mutação. _options_ pode ter `root: true` que permite confirmar mutações da raiz em [módulos namespaced](../guide/modules.md#namespacing). [Detalhes](../guide/mutations.md) ### dispatch - `dispatch(type: string, payload?: any, options?: Object): Promise` - `dispatch(action: Object, options?: Object): Promise` - Despacha uma ação. _options_ pode ter _root: true_ que permite despachar ações para raiz em [módulos namespaced](../guide/modules.md#namespacing). Retorna um _Promise_ que resolve todos os manipuladores de ação acionados. [Detalhes](../guide/actions.md) + Despacha uma ação. _options_ pode ter `root: true` que permite despachar ações para raiz em [módulos namespaced](../guide/modules.md#namespacing). Retorna um _Promise_ que resolve todos os manipuladores de ação acionados. [Detalhes](../guide/actions.md) ### replaceState @@ -229,7 +229,7 @@ const store = new Vuex.Store({ ...options }) Registra um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-modulo-dinamico) - _options_ can have _preserveState: true_ que permite preservar o estado anterior. Útil com renderização do lado do servidor (_server-side-rendering_). + _options_ can have `preserveState: true` que permite preservar o estado anterior. Útil com renderização do lado do servidor (_server-side-rendering_). ### unregisterModule @@ -287,4 +287,4 @@ const store = new Vuex.Store({ ...options }) - `createNamespacedHelpers(namespace: string): Object` - Cria um componente _namespaced_ dos métodos auxiliares. O objeto retornado possui _mapState_, _mapGetters_, _mapActions_ e _mapMutations_, que estão conectados com o dado _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace) + Cria um componente _namespaced_ dos métodos auxiliares. O objeto retornado possui `mapState`, `mapGetters`, `mapActions` e `mapMutations`, que estão conectados com o dado _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace) diff --git a/docs/ptbr/guide/README.md b/docs/ptbr/guide/README.md index c4f3e4756..2d15f679d 100644 --- a/docs/ptbr/guide/README.md +++ b/docs/ptbr/guide/README.md @@ -31,7 +31,7 @@ const store = new Vuex.Store({ }) ``` -Agora, você pode acessar o objeto de estado como _store.state_ e acionar uma mudança de estado com o método _store.commit_: +Agora, você pode acessar o objeto de estado como `store.state` e acionar uma mudança de estado com o método `store.commit`: ``` js store.commit('increment') @@ -39,10 +39,10 @@ store.commit('increment') console.log(store.state.count) // -> 1 ``` -Novamente, a razão pela qual estamos confirmando (ou fazendo _commit_ de) uma mutação em vez de mudar _store.state.count_ diretamente, é porque queremos rastreá-la explicitamente. Esta convenção simples torna sua intenção mais explícita, de modo que você possa ter melhores argumetos sobre as mudanças de estado em seu aplicativo ao ler o código. Além disso, isso nos dá a oportunidade de implementar ferramentas que podem registrar cada mutação, capturar momentos do estado ou mesmo realizar depuração viajando pelo histórico de estado (_time travel_). +Novamente, a razão pela qual estamos confirmando (ou fazendo _commit_ de) uma mutação em vez de mudar `store.state.count` diretamente, é porque queremos rastreá-la explicitamente. Esta convenção simples torna sua intenção mais explícita, de modo que você possa ter melhores argumetos sobre as mudanças de estado em sua aplicação ao ler o código. Além disso, isso nos dá a oportunidade de implementar ferramentas que podem registrar cada mutação, capturar momentos do estado ou mesmo realizar depuração viajando pelo histórico de estado (_time travel_). Usar o estado do _store_ em um componente simplesmente envolve o retorno do estado dentro de um dado computado, porque o estado do _store_ é reativo. Acionar alterações simplesmente significa confirmar (ou fazer _commit_ de) mutações nos métodos dos componentes. -Aqui está um exemplo do [aplicativo de contador do Vuex mais básico](https://jsfiddle.net/n9jmu5v7/1269/). +Aqui está um exemplo da [aplicação de contador do Vuex mais básico](https://jsfiddle.net/n9jmu5v7/1269/). Em seguida, discutiremos cada conceito chave em mais detalhes, começando com [Estado](state.md). diff --git a/docs/ptbr/guide/actions.md b/docs/ptbr/guide/actions.md index 506d4d84c..ead8f153b 100644 --- a/docs/ptbr/guide/actions.md +++ b/docs/ptbr/guide/actions.md @@ -27,7 +27,7 @@ const store = new Vuex.Store({ }) ``` -Os manipuladores de ação recebem um objeto _context_ que expõe o mesmo conjunto de métodos/propriedades na instância do _store_, para que você possa chamar _context.commit_ para confirmar uma mutação ou acessar o estado e os _getters_ através do _context.state_ e do _context.getters_. Veremos por que esse objeto _context_ não é a própria instância do _store_ quando apresentarmos [Módulos](modules.md) mais tarde. +Os manipuladores de ação recebem um objeto _context_ que expõe o mesmo conjunto de métodos/propriedades na instância do _store_, para que você possa chamar `context.commit` para confirmar uma mutação ou acessar o estado e os _getters_ através do `context.state` e do `context.getters`. Veremos por que esse objeto _context_ não é a própria instância do _store_ quando apresentarmos [Módulos](modules.md) mais tarde. Na prática, muitas vezes usamos ES2015 [desestruturação de argumentos](https://github.com/lukehoban/es6features#destructuring) para simplificar um pouco o código (especialmente quando precisamos usar _commit_ várias vezes): @@ -41,7 +41,7 @@ actions: { ### Ações de Despacho -As ações são acionadas com o método _store.dispatch_: +As ações são acionadas com o método `store.dispatch`: ``` js store.dispatch('increment') @@ -100,7 +100,7 @@ Observe que estamos realizando um fluxo de operações assíncronas, e gravando ### Ações de Despacho em Componentes -Você pode despachar ações em componentes com `this.$store.dispatch('xxx')`, ou usar o auxiliar _mapActions_ que mapeia métodos do componente para chamadas do _store.dispatch_ (esta ação requer injeção do _store_ na instância raiz): +Você pode despachar ações em componentes com `this.$store.dispatch('xxx')`, ou usar o auxiliar _mapActions_ que mapeia métodos do componente para chamadas do `store.dispatch` (esta ação requer injeção do _store_ na instância raiz): ``` js import { mapActions } from 'vuex' @@ -125,7 +125,7 @@ export default { As ações geralmente são assíncronas, então como sabemos quando uma ação é realizada? E mais importante, como podemos compor ações múltiplas em conjunto para lidar com fluxos assíncronos mais complexos? -A primeira coisa a saber é que o _store.dispatch_ pode manipular o _Promise_ retornado pelo manipulador de ação acionado e também retorna _Promise_: +A primeira coisa a saber é que o `store.dispatch` pode manipular o _Promise_ retornado pelo manipulador de ação acionado e também retorna _Promise_: ``` js actions: { @@ -177,4 +177,4 @@ actions: { } ``` -> É possível para um _store.dispatch_ desencadear vários manipuladores de ação em diferentes módulos. Neste caso, o valor retornado será um _Promise_ que resolve quando todos os manipuladores desencadeados foram resolvidos. +> É possível para um `store.dispatch` desencadear vários manipuladores de ação em diferentes módulos. Neste caso, o valor retornado será um _Promise_ que resolve quando todos os manipuladores desencadeados foram resolvidos. diff --git a/docs/ptbr/guide/getters.md b/docs/ptbr/guide/getters.md index bc0922f4d..1d4c5fde2 100644 --- a/docs/ptbr/guide/getters.md +++ b/docs/ptbr/guide/getters.md @@ -36,13 +36,13 @@ const store = new Vuex.Store({ ### Acesso Estilo-Propriedade -Os _getters_ serão expostos no objeto _store.getters_ e você acessa valores como propriedades: +Os _getters_ serão expostos no objeto `store.getters` e você acessa valores como propriedades: ``` js store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }] ``` -Os _getters_ também receberão outros _getters_ como o 2º argumento: +Os _getters_ também receberão outros `getters` como o 2º argumento: ``` js getters: { diff --git a/docs/ptbr/guide/modules.md b/docs/ptbr/guide/modules.md index 269d64acc..3544450f1 100644 --- a/docs/ptbr/guide/modules.md +++ b/docs/ptbr/guide/modules.md @@ -2,7 +2,7 @@

Tente esta lição no Scrimba
-Devido ao uso de uma única árvore de estado, todo o estado de nossa aplicação está contido dentro de um grande objeto. No entanto, à medida que nosso aplicativo cresce em escala, o _store_ pode ficar realmente inchado. +Devido ao uso de uma única árvore de estado, todo o estado de nossa aplicação está contido dentro de um grande objeto. No entanto, à medida que nossa aplicação cresce em escala, o _store_ pode ficar realmente inchado. Para ajudar com isso, o Vuex nos permite dividir nosso _store_ em **módulos**. Cada módulo pode conter seu próprio estado, mutações, ações, _getters_ e até módulos aninhados - é todo o complexo caminho abaixo: @@ -55,7 +55,7 @@ const moduleA = { } ``` -Da mesma forma, dentro das ações do módulo, _context.state_ irá expor o estado local, e o estado raiz será exposto como _context.rootState_: +Da mesma forma, dentro das ações do módulo, `context.state` irá expor o estado local, e o estado raiz será exposto como `context.rootState`: ``` js const moduleA = { @@ -87,7 +87,7 @@ const moduleA = { Por padrão, ações, mutações e _getters_ dentro dos módulos ainda são registrados sob o **_namespace_ global** - isso permite que vários módulos reajam ao mesmo tipo de ação/mutação. -Se você quer que seus módulos sejam mais independentes ou reutilizáveis, você pode marcá-los como _namespaced_ com _namespaced: true_. Quando o módulo é registrado, todos os _getters_, ações e mutações serão automaticamente _namespaced_ com base no caminho no qual o módulo está registrado. Por exemplo: +Se você quer que seus módulos sejam mais independentes ou reutilizáveis, você pode marcá-los como _namespaced_ com `namespaced: true`. Quando o módulo é registrado, todos os _getters_, ações e mutações serão automaticamente _namespaced_ com base no caminho no qual o módulo está registrado. Por exemplo: ``` js const store = new Vuex.Store({ @@ -136,7 +136,7 @@ Os _getters_ e as ações _namespaced_ receberão _getters_, _dispatch_ e _commi #### Acessando Recursos Globais em Módulos Namespaced -Se você quiser usar estado global e _getters_, _rootState_ e _rootGetters_ são passados como o 3º e 4º argumentos para funções _getter_, e também expostos como propriedades no objeto _context_ passado para funções de ação. +Se você quiser usar estado global e _getters_, `rootState` e `rootGetters` são passados como o 3º e 4º argumentos para funções _getter_, e também expostos como propriedades no objeto _context_ passado para funções de ação. Para despachar ações confirmar (ou fazer um _commit_ de) mutações no _namespace_ global, passe `{root: true}` como o 3º argumento para _dispatch_ e _commit_. @@ -176,7 +176,7 @@ modules: { #### Registrar Ação Global em Módulos com Namespaces -Se você quiser registrar ações globais em módulos com namespaces, você pode marcá-lo com _root: true_ e colocar a definição de ação na função _handler_. Por exemplo: +Se você quiser registrar ações globais em módulos com namespaces, você pode marcá-lo com `root: true` e colocar a definição de ação na função _handler_. Por exemplo: ``` js { @@ -202,7 +202,7 @@ Se você quiser registrar ações globais em módulos com namespaces, você pode #### Usando Métodos Auxiliares com Namespace -Ao vincular um módulo com _namespace_ aos componentes com os auxiliares _mapState_, _mapGetters_, _mapActions_ e _mapMutations_, ele pode ficar um pouco verboso: +Ao vincular um módulo com _namespace_ aos componentes com os auxiliares `mapState`, `mapGetters`, `mapActions` e `mapMutations`, ele pode ficar um pouco verboso: ``` js computed: { @@ -280,7 +280,7 @@ export function createPlugin (options = {}) { ### Registro de Módulo Dinâmico -Você pode registrar um módulo **após** o _store_ ser criado com o método _store.registerModule_: +Você pode registrar um módulo **após** o _store_ ser criado com o método `store.registerModule`: ``` js // registra um módulo `myModule` @@ -294,15 +294,15 @@ store.registerModule(['nested', 'myModule'], { }) ``` -Os estados do módulo serão expostos como _store.state.myModule_ e _store.state.nested.myModule_. +Os estados do módulo serão expostos como `store.state.myModule` e `store.state.nested.myModule`. -O registro de módulo dinâmico possibilita que outros plug-ins Vue aproveitem também o Vuex para gerenciamento de estado, anexando um módulo ao _store_ do aplicativo. Por exemplo, a biblioteca [`vuex-router-sync`](https://github.com/vuejs/vuex-router-sync) integra o vue-router com o vuex gerenciando o estado da rota do aplicativo em um módulo conectado dinamicamente. +O registro de módulo dinâmico possibilita que outros _plugins_ Vue aproveitem também o Vuex para gerenciamento de estado, anexando um módulo ao _store_ da aplicação. Por exemplo, a biblioteca [`vuex-router-sync`](https://github.com/vuejs/vuex-router-sync) integra o vue-router com o vuex gerenciando o estado da rota da aplicação em um módulo conectado dinamicamente. Você também pode remover um módulo dinamicamente registrado com o `store.unregisterModule(moduleName)`. Note que você não pode remover módulos estáticos (declarados na criação do _store_) com este método. #### Preservando o estado -É bem provável que você queira preservar o estado anterior ao registrar um novo módulo, como preservar o estado de um aplicativo Renderizado no Lado do Servidor (_Server_ _Side_ _Rendered_). Você pode fazer isso com a opção `preserveState`:`store.registerModule('a', module, {preserveState: true})` +É bem provável que você queira preservar o estado anterior ao registrar um novo módulo, como preservar o estado de uma aplicação Renderizada no Lado do Servidor (_Server_ _Side_ _Rendered_). Você pode fazer isso com a opção `preserveState`:`store.registerModule('a', module, {preserveState: true})` Quando você informa `preserveState: true`, o módulo é registrado, as ações, mutações e _getters_ são incluídos no _store_, mas o estado não. É assumido que estado da sua _store_ já contém um estado para aquele módulo e você não quer sobrescrevê-lo. @@ -310,7 +310,7 @@ Quando você informa `preserveState: true`, o módulo é registrado, as ações, Às vezes, podemos precisar criar várias instâncias de um módulo, por exemplo: -- Criando multiplos _stores_ que usam o mesmo módulo (e.g. Para [evitar Singletons com informações de estado no SSR](https://ssr.vuejs.org/en/structure.html#avoid-stateful-singletons) quando a opção _runInNewContext_ é _false_ ou `'_once_'`); +- Criando multiplos _stores_ que usam o mesmo módulo (e.g. Para [evitar Singletons com informações de estado no SSR](https://ssr.vuejs.org/en/structure.html#avoid-stateful-singletons) quando a opção `runInNewContext` é `false` ou `'_once_'`); - Registrar o mesmo módulo várias vezes no mesmo _store_. Se usarmos um objeto simples para declarar o estado do módulo, esse objeto de estado será compartilhado por referência e causará poluição entre estados de _store_/módulo quando ele sofrer uma mutação. diff --git a/docs/ptbr/guide/mutations.md b/docs/ptbr/guide/mutations.md index 924ca4a38..a8d4dabd9 100644 --- a/docs/ptbr/guide/mutations.md +++ b/docs/ptbr/guide/mutations.md @@ -18,7 +18,7 @@ const store = new Vuex.Store({ }) ``` -Você não pode chamar diretamente um manipulador de mutação. Pense nisso mais como registro de evento: "Quando uma mutação com o tipo _increment_ é acionada, chame este manipulador." Para invocar um manipulador de mutação, você precisa chamar _store.commit_ com seu tipo: +Você não pode chamar diretamente um manipulador de mutação. Pense nisso mais como registro de evento: "Quando uma mutação com o tipo _increment_ é acionada, chame este manipulador." Para invocar um manipulador de mutação, você precisa chamar `store.commit` com seu tipo: ``` js store.commit('increment') @@ -26,7 +26,7 @@ store.commit('increment') ### Commit com Payload -Você pode passar um argumento adicional para o _store.commit_, que é chamado de **_payload_** para a mutação: +Você pode passar um argumento adicional para o `store.commit`, que é chamado de **_payload_** para a mutação: ``` js // ... @@ -96,7 +96,7 @@ Como o estado de um _store_ Vuex é reativado pelo Vue, quando alteramos o estad ### Usando Constantes para Tipos de Mutação -É um padrão comumente visto usar constantes para tipos de mutação em várias implementações do _Flux_. Isso permite que o código aproveite as ferramentas como os _linters_, e colocar todas as constantes em um único arquivo permite que seus colaboradores tenham uma visão geral das mutações possíveis em todo o aplicativo: +É um padrão comumente visto usar constantes para tipos de mutação em várias implementações do _Flux_. Isso permite que o código aproveite as ferramentas como os _linters_, e colocar todas as constantes em um único arquivo permite que seus colaboradores tenham uma visão geral das mutações possíveis em toda a aplicação: ``` js // mutation-types.js @@ -136,11 +136,11 @@ mutations: { } ``` -Agora imagine que estamos depurando o aplicativo e observando os logs de mutação do devtool. Para cada mutação registrada, o devtool precisará capturar os momentos "antes" e "depois" do estado. No entanto, o _callback_ assíncrono dentro da mutação de exemplo acima torna isso impossível: o _callback_ ainda não é chamado quando a mutação é confirmada (ou o _commit_ da mutação é feito) e não há como o devtool saber quando o _callback_ será realmente chamado - qualquer mutação de estado executada no _callback_ é essencialmente impossível de rastrear! +Agora imagine que estamos depurando a aplicação e observando os logs de mutação do devtool. Para cada mutação registrada, o devtool precisará capturar os momentos "antes" e "depois" do estado. No entanto, o _callback_ assíncrono dentro da mutação de exemplo acima torna isso impossível: o _callback_ ainda não é chamado quando a mutação é confirmada (ou o _commit_ da mutação é feito) e não há como o devtool saber quando o _callback_ será realmente chamado - qualquer mutação de estado executada no _callback_ é essencialmente impossível de rastrear! ### Confirmando (ou fazendo Commits de) Mutações em Componentes -Você pode confirmar (ou fazer _commit_ de) mutações em componentes com `this.$store.commit('xxx')`, ou use o auxiliar `mapMutations` que mapeia métodos de componentes para chamadas _store.commit_ (requer injeção _store_ raiz): +Você pode confirmar (ou fazer _commit_ de) mutações em componentes com `this.$store.commit('xxx')`, ou use o auxiliar `mapMutations` que mapeia métodos de componentes para chamadas `store.commit` (requer injeção _store_ raiz): ``` js import { mapMutations } from 'vuex' diff --git a/docs/ptbr/guide/plugins.md b/docs/ptbr/guide/plugins.md index b9c0f3925..d9204d0ee 100644 --- a/docs/ptbr/guide/plugins.md +++ b/docs/ptbr/guide/plugins.md @@ -83,7 +83,7 @@ const store = new Vuex.Store({ }) ``` -O _plugin_ vai ser usado por padrão. Para produção, você vai precisar do [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) para webpack ou [envify](https://github.com/hughsk/envify) para Browserify para converter o valor do `process.env.NODE_ENV !== 'production'` para _false_ no _build_ final. +O _plugin_ vai ser usado por padrão. Para produção, você vai precisar do [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) para webpack ou [envify](https://github.com/hughsk/envify) para Browserify para converter o valor do `process.env.NODE_ENV !== 'production'` para `false` no _build_ final. ### Plugin de Log Integrado diff --git a/docs/ptbr/guide/state.md b/docs/ptbr/guide/state.md index 70a7f4d6a..426c8876d 100644 --- a/docs/ptbr/guide/state.md +++ b/docs/ptbr/guide/state.md @@ -4,7 +4,7 @@ -O Vuex usa uma **árvore única de estado** - ou seja, esse único objeto contém todo o estado do seu nível de aplicação e serve como a "única fonte da verdade". Isso também significa que você terá apenas um _store_ para cada aplicativo. Uma árvore única de estado facilita a localização de uma parte específica do estado, e permite capturar facilmente momentos do estado atual do aplicativo para fins de depuração. +O Vuex usa uma **árvore única de estado** - ou seja, esse único objeto contém todo o estado do seu nível de aplicação e serve como a "única fonte da verdade". Isso também significa que você terá apenas um _store_ para cada aplicação. Uma árvore única de estado facilita a localização de uma parte específica do estado, e permite capturar facilmente momentos do estado atual da aplicação para fins de depuração. A árvore única de estado não entra em conflito com a modularidade - em capítulos posteriores, discutiremos como dividir seu estado e mutações em sub-módulos. @@ -26,9 +26,9 @@ const Counter = { } ``` -Sempre que o _store.state.count_ muda, fará com que o dado computado seja reavaliado e ative as atualizações de _DOM_ associadas. +Sempre que o `store.state.count` muda, fará com que o dado computado seja reavaliado e ative as atualizações de DOM associadas. -No entanto, esse padrão faz com que o componente dependa do _store_ _singleton_ global. Ao usar um sistema de módulo, ele precisa importar o _store_ em todos os componentes que usam o estado do _store_ e também requer _mocking_ ao testar o componente. +No entanto, esse padrão faz com que o componente dependa do _store_ _singleton_ global. Ao usar um sistema de módulo, ele precisa importar o _store_ em todos os componentes que usam o estado do _store_ e também requer requer dados fictícios (ou _mocking_) ao testar o componente. O Vuex fornece um mecanismo para "injetar" o _store_ em todos os componentes filho do componente raiz com a opção _store_ (habilitada por `Vue.use(Vuex)`): @@ -87,7 +87,7 @@ export default { } ``` -Também podemos passar um _Array_ de _Strings_ para _mapState_ quando o nome de um dado computado mapeado é o mesmo que um nome de árvore secundária do estado. +Também podemos passar um _Array_ de _Strings_ para `mapState` quando o nome de um dado computado mapeado é o mesmo que um nome de árvore secundária do estado. ``` js computed: mapState([ diff --git a/docs/ptbr/guide/strict.md b/docs/ptbr/guide/strict.md index e07c3f653..0595177db 100644 --- a/docs/ptbr/guide/strict.md +++ b/docs/ptbr/guide/strict.md @@ -1,6 +1,6 @@ # Modo Estrito -Para habilitar o modo estrito, simplesmente passe _strict: true_ ao criar um _store_ Vuex: +Para habilitar o modo estrito, simplesmente passe `strict: true` ao criar um _store_ Vuex: ``` js const store = new Vuex.Store({ diff --git a/docs/ptbr/guide/structure.md b/docs/ptbr/guide/structure.md index b5cac0b86..4cbf4d4c1 100644 --- a/docs/ptbr/guide/structure.md +++ b/docs/ptbr/guide/structure.md @@ -2,7 +2,7 @@ O Vuex não restringe realmente como você estrutura seu código. Em vez disso, ele impõe um conjunto de princípios de alto nível: -1. O estado do nível do aplicativo é centralizado no _store_. +1. O estado do nível da aplicação é centralizado no _store_. 2. A única maneira de mudar o estado é confirmando (ou fazendo _commit_ das) **mutações**, que são transações síncronas @@ -10,7 +10,7 @@ O Vuex não restringe realmente como você estrutura seu código. Em vez disso, Enquanto você seguir estas regras, depende de você como estruturar seu projeto. Se o arquivo do seu _store_ for muito grande, basta começar a dividir as ações, mutações e _getters_ em arquivos separados. -Para qualquer aplicativo não trivial, provavelmente precisaremos aproveitar os módulos. Aqui está um exemplo de estrutura de projeto: +Para qualquer aplicação mais complexa, provavelmente precisaremos aproveitar os módulos. Aqui está um exemplo de estrutura de projeto: ``` bash ├── index.html diff --git a/docs/ru/README.md b/docs/ru/README.md index 29dbc3958..00590087b 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -4,7 +4,7 @@ Vuex — **паттерн управления состоянием + библиотека** для приложений на Vue.js. Он служит централизованным хранилищем данных для всех компонентов приложения с правилами, гарантирующими, что состояние может быть изменено только предсказуемым образом. Vuex интегрируется с официальным расширением [vue-devtools](https://github.com/vuejs/vue-devtools), предоставляя «из коробки» такие продвинутые возможности, как «машину времени» для отладки и экспорт/импорт слепков состояния данных. -### Что такое «паттерн управления состоянием»? +## Что такое «паттерн управления состоянием»? Давайте начнём с простого приложения Vue, реализующего счётчик: @@ -41,7 +41,7 @@ new Vue({

-Однако простота быстро исчезает, когда у нас появляется **нескольких компонентов, основывающихся на одном и том же состоянии**: +Однако простота быстро исчезает, когда у нас появляется **несколько компонентов, основывающихся на одном и том же состоянии**: * Несколько представлений могут зависеть от одной и той же части состояния приложения. * Действия из разных представлений могут оказывать влияние на одни и те же части состояния приложения. @@ -58,7 +58,7 @@ new Vue({ ![vuex](/ru/vuex.png) -### Когда следует использовать Vuex? +## Когда следует использовать Vuex? Vuex помогает управлять совместно используемым состоянием ценой привнесения новых концепций и вспомогательного кода. Компромисс, когда кратковременная продуктивность страдает на благо долгосрочной. diff --git a/docs/ru/api/README.md b/docs/ru/api/README.md index 6d6de240b..33f693883 100644 --- a/docs/ru/api/README.md +++ b/docs/ru/api/README.md @@ -176,13 +176,16 @@ const store = new Vuex.Store({ ...options }); * `subscribe(handler: Function, options?: Object): Function` -Отслеживание вызова мутаций хранилища. Обработчик `handler` вызывается после каждой мутации и получает в качестве параметров дескриптор мутации и состояние после мутации: +Отслеживание вызова мутаций хранилища. Обработчик `handler` вызывается после каждой мутации и получает в качестве параметров дескриптор мутации и состояние после мутации. ```js -store.subscribe((mutation, state) => { - console.log(mutation.type); - console.log(mutation.payload); -}); +const unsubscribe = store.subscribe((mutation, state) => { + console.log(mutation.type) + console.log(mutation.payload) +}) + +// для остановки отслеживания нужно вызвать unsubscribe +unsubscribe() ``` По умолчанию, новый обработчик добавляется в конец цепочки, поэтому он будет выполняться после других обработчиков, добавленных раньше. Это поведение можно переопределить добавив `prepend: true` в `options`, что позволит добавлять обработчик в начало цепочки. @@ -191,7 +194,7 @@ store.subscribe((mutation, state) => { store.subscribe(handler, { prepend: true }) ``` -Для прекращения отслеживания, необходимо вызвать возвращаемую методом функцию. +Метод `subscribe` возвращает функцию `unsubscribe`, которую требуется вызывать когда отслеживание больше не требуется. Например, можно подписаться на модуль Vuex и прекращать отслеживание при удалении регистрации модуля. Или можно вызвать `subscribe` внутри компонента Vue, а позднее уничтожить компонент. В таких случаях, необходимо вручную останавливать отслеживание. Чаще всего используется в плагинах. [Подробнее](../guide/plugins.md) @@ -201,13 +204,18 @@ store.subscribe(handler, { prepend: true }) > Добавлено в версии 2.5.0 -Отслеживание вызова действий хранилища. Обработчик `handler` вызывается после каждого действия и получает в качестве параметров дескриптор действия и текущее состояние хранилища: +Отслеживание вызова действий хранилища. Обработчик `handler` вызывается после каждого действия и получает в качестве параметров дескриптор действия и текущее состояние хранилища. + +Метод `subscribe` возвращает функцию `unsubscribe`, которую требуется вызывать когда отслеживание больше не требуется. Например, при удалении регистрации модуля Vuex или перед уничтожением компонента Vue. ```js -store.subscribeAction((action, state) => { - console.log(action.type); - console.log(action.payload); -}); +const unsubscribe = store.subscribeAction((action, state) => { + console.log(action.type) + console.log(action.payload) +}) + +// для остановки отслеживания нужно вызвать unsubscribe +unsubscribe() ``` По умолчанию, новый обработчик добавляется в конец цепочки, поэтому он будет выполняться после других обработчиков, добавленных раньше. Это поведение можно переопределить добавив `prepend: true` в `options`, что позволит добавлять обработчик в начало цепочки. @@ -216,7 +224,7 @@ store.subscribeAction((action, state) => { store.subscribeAction(handler, { prepend: true }) ``` -Для прекращения отслеживания, необходимо вызвать возвращаемую методом функцию. +Метод `subscribe` возвращает функцию `unsubscribe`, которую требуется вызывать когда отслеживание больше не требуется. Например, можно подписаться на модуль Vuex и прекращать отслеживание при удалении регистрации модуля. Или можно вызвать `subscribe` внутри компонента Vue, а позднее уничтожить компонент. В таких случаях, необходимо вручную останавливать отслеживание. > Добавлено в версии 3.1.0 @@ -237,7 +245,7 @@ store.subscribeAction({ С версии 3.4.0 в `subscribeAction` также можно указывать обработчик `error` для перехвата ошибки, выброшенной при выполнении действия. В качестве третьего аргумента функция получает объект `error`. -``` js +```js store.subscribeAction({ error: (action, state, error) => { console.log(`error action ${action.type}`) diff --git a/docs/ru/guide/README.md b/docs/ru/guide/README.md index 173771d3a..f00242b9d 100644 --- a/docs/ru/guide/README.md +++ b/docs/ru/guide/README.md @@ -8,7 +8,7 @@ 2. Нельзя напрямую изменять состояние хранилища. Единственный способ внести изменения — явно **вызвать мутацию**. Это гарантирует, что любое изменение состояния оставляет след и позволяет использовать инструментарий, чтобы лучше понимать ход работы приложения. -### Простейшее хранилище +## Простейшее хранилище :::tip ЗАМЕЧАНИЕ В примерах кода документации используется синтаксис ES2015. Если вы с ним ещё не знакомы, [сейчас самое время изучить](https://babeljs.io/docs/learn-es2015/)! @@ -16,6 +16,8 @@ После [установки](../installation.md) Vuex, давайте создадим хранилище. Это довольно просто — необходимо указать начальный объект состояния и некоторые мутации: +### Vuex 3.x (для Vue 2) + ```js import Vue from 'vue' import Vuex from 'vuex' @@ -34,6 +36,23 @@ const store = new Vuex.Store({ }) ``` +### Vuex 4.x (для Vue 3) + +```js +import { createStore } from 'vuex' +import { createApp } from 'vue' + +const store = createStore({ + state () { + return { + count: 1 + } + } +}) +const app = createApp({ /* ваш корневой компонент */ }) +app.use(store) +``` + Теперь можно получить доступ к объекту состояния через `store.state` и вызвать изменение состояния с помощью метода `store.commit`: ```js diff --git a/docs/ru/guide/actions.md b/docs/ru/guide/actions.md index 3c75343c7..c55177e57 100644 --- a/docs/ru/guide/actions.md +++ b/docs/ru/guide/actions.md @@ -39,7 +39,7 @@ actions: { } ``` -### Диспетчеризация действий +## Диспетчеризация действий Действия запускаются методом `store.dispatch`: @@ -98,7 +98,7 @@ actions: { Таким образом удаётся организовать поток асинхронных операций, записывая побочные эффекты действий в виде мутаций состояния. -### Диспетчеризация действий в компонентах +## Диспетчеризация действий в компонентах Диспетчеризировать действия в компонентах можно при помощи `this.$store.dispatch('xxx')` или используя вспомогательную функцию `mapActions`, создающую локальные псевдонимы для действий в виде методов компонента (требуется наличие корневого `$store`): @@ -121,7 +121,7 @@ export default { }; ``` -### Композиция действий +## Композиция действий Раз действия зачастую асинхронны, то как узнать, что действие уже завершилось? И, что важнее, как быть со связанными между собой действиями при организации более сложных асинхронных потоков? diff --git a/docs/ru/guide/forms.md b/docs/ru/guide/forms.md index 239c16ef2..70fb8f2d3 100644 --- a/docs/ru/guide/forms.md +++ b/docs/ru/guide/forms.md @@ -41,7 +41,7 @@ mutations: { } ``` -### Двунаправленные вычисляемые свойства +## Двунаправленные вычисляемые свойства Заметно, что получившаяся выше запись — куда многословнее, чем используемая в связке `v-model` с локальным состоянием, да и некоторые полезные возможности `v-model` мы таким образом упускаем. В качестве альтернативы можно предложить использование двунаправленного вычисляемого свойства с сеттером: diff --git a/docs/ru/guide/getters.md b/docs/ru/guide/getters.md index b04f228d6..214bfc38a 100644 --- a/docs/ru/guide/getters.md +++ b/docs/ru/guide/getters.md @@ -34,7 +34,7 @@ const store = new Vuex.Store({ }); ``` -### Стиль обращения как к свойствам +## Стиль обращения как к свойствам Геттеры доступны в объекте `store.getters`, и вы можете получить доступ к значениям как свойствам: @@ -69,7 +69,7 @@ computed: { Обратите внимание, что геттеры, доступ к которым выполняется как к свойствам, будут кэшироваться как часть системы реактивности Vue. -### Стиль обращения как к методам +## Стиль обращения как к методам Можно также передавать аргументы геттерам, возвращая функцию. Это например пригодится, когда необходимо возвращать массив по указанному критерию: @@ -88,7 +88,7 @@ store.getters.getTodoById(2); // -> { id: 2, text: '...', done: false } Обратите внимание, что геттеры, доступ к которым выполняется как к методам, будут запускаться каждый раз при их вызове, а результаты не будут кэшироваться. -### Вспомогательная функция `mapGetters` +## Вспомогательная функция `mapGetters` Функция `mapGetters` просто проксирует геттеры хранилища в локальные вычисляемые свойства компонента: diff --git a/docs/ru/guide/modules.md b/docs/ru/guide/modules.md index 5c8a79854..3af406682 100644 --- a/docs/ru/guide/modules.md +++ b/docs/ru/guide/modules.md @@ -2,7 +2,7 @@ -Из-за использования единого дерева состояния, все глобальные данные приложения оказываются помещены в один большой объект. По мере роста приложения, хранилище может существенно раздуться. +Благодаря использованию единого дерева состояния, все состояния приложения содержатся внутри одного большого объекта. Однако, по мере роста и масштабировании приложения, хранилище может существенно раздуться. Чтобы помочь в этой беде, Vuex позволяет разделять хранилище на **модули**. Каждый модуль может содержать собственное состояние, мутации, действия, геттеры и даже встроенные подмодули — структура фрактальна: @@ -31,7 +31,7 @@ store.state.a // -> состояние модуля `moduleA` store.state.b // -> состояние модуля `moduleB` ``` -### Локальное состояние модулей +## Локальное состояние модулей Первым аргументом, который получает мутации и геттеры, будет **локальное состояние модуля**. @@ -83,7 +83,7 @@ const moduleA = { }; ``` -### Пространства имён +## Пространства имён По умолчанию действия, мутации и геттеры внутри модулей регистрируются в **глобальном пространстве имён** — это позволяет нескольким модулям реагировать на тот же тип мутаций/действий. @@ -134,7 +134,7 @@ const store = new Vuex.Store({ Геттеры и действия с собственным пространством имён будут получать свои локальные `getters`, `dispatch` и `commit`. Другими словами, вы можете использовать содержимое модуля без написания префиксов в том же модуле. Переключения между пространствами имён не влияет на код внутри модуля. -#### Доступ к глобальному содержимому в модулях со своим пространством имён +### Доступ к глобальному содержимому в модулях со своим пространством имён Если вы хотите использовать глобальное состояние и геттеры, `rootState` и `rootGetters` передаются 3-м и 4-м аргументами в функции геттеров, а также как свойства в объекте `context`, передаваемом в функции действий. @@ -176,7 +176,7 @@ modules: { } ``` -#### Регистрация глобального действия в модуле с собственным пространством имён +### Регистрация глобального действия в модуле с собственным пространством имён Если вы хотите зарегистрировать глобальное действие в модуле с собственным пространством имён, вы можете пометить его с помощью `root: true` и поместить определение действия в функцию `handler`. Например: @@ -202,7 +202,7 @@ modules: { } ``` -#### Подключение с помощью вспомогательных функций к пространству имён +### Подключение с помощью вспомогательных функций к пространству имён Подключение модуля со своим пространством имён к компонентам с помощью вспомогательных функций `mapState`, `mapGetters`, `mapActions` и `mapMutations` это может выглядеть подобным образом: @@ -268,7 +268,7 @@ export default { }; ``` -#### Уточнение для разработчиков плагинов +### Уточнение для разработчиков плагинов Вас может обеспокоить непредсказуемость пространства имён для ваших модулей, когда вы создаёте [плагин](plugins.md) с собственными модулями и возможностью пользователям добавлять их в хранилище Vuex. Ваши модули будут также помещены в пространство имён, если пользователи плагина добавляют ваши модули в модуль со своим пространством имён. Чтобы приспособиться к этой ситуации, вам может потребоваться получить значение пространства имён через настройки плагина: @@ -284,7 +284,7 @@ export function createPlugin(options = {}) { } ``` -### Динамическая регистрация модулей +## Динамическая регистрация модулей Вы можете зарегистрировать модуль уже и **после** того, как хранилище было создано, используя метод `store.registerModule`: @@ -312,13 +312,13 @@ store.registerModule(['nested', 'myModule'], { Обратите внимание, что можно проверить, зарегистрирован ли уже модуль с заданным именем с помощью метода `store.hasModule(moduleName)`. -#### Сохранение состояния +### Сохранение состояния Вероятно, вы хотите сохранить предыдущее состояние при регистрации нового модуля, например сохранить состояние из приложения с рендерингом на стороне сервера. Вы можете этого добиться с помощью опции `preserveState`: `store.registerModule('a', module, { preserveState: true })`. При использовании `preserveState: true` модуль регистрируется, действия, мутации и геттеры добавляются в хранилище, а состояние нет. Предполагается, что состояние вашего хранилища уже содержит состояние для этого модуля и нет необходимости его перезаписывать. -### Повторное использование модулей +## Повторное использование модулей Иногда нам может потребоваться создать несколько экземпляров модуля, например: diff --git a/docs/ru/guide/mutations.md b/docs/ru/guide/mutations.md index b6e4df042..0a3d7dc2c 100644 --- a/docs/ru/guide/mutations.md +++ b/docs/ru/guide/mutations.md @@ -24,7 +24,7 @@ const store = new Vuex.Store({ store.commit('increment'); ``` -### Мутации с нагрузкой +## Мутации с нагрузкой При вызове `store.commit` в мутацию можно также передать дополнительный параметр, называемый **нагрузкой (`payload`)**: @@ -58,7 +58,7 @@ store.commit('increment', { }); ``` -### Объектный синтаксис +## Объектный синтаксис Другой способ вызвать мутацию — это передать в commit единственный параметр, в котором `type` указан напрямую: @@ -79,7 +79,7 @@ mutations: { } ``` -### Мутации следуют правилам реактивности Vue +## Мутации следуют правилам реактивности Vue Поскольку состояние хранилища Vuex — это реактивная переменная Vue, при возникновении мутации зависящие от этого состояния компоненты Vue обновляются автоматически. Кроме того, это значит, что мутации Vuex имеют те же самые подводные камни, что и реактивность в обычном Vue: @@ -95,7 +95,7 @@ mutations: { state.obj = { ...state.obj, newProp: 123 }; ``` -### Использование констант для обозначения типов мутаций +## Использование констант для обозначения типов мутаций В различных вариантах реализации Flux этот подход используется весьма часто. Вынесите все константы с типами мутаций и действий в отдельный файл, чтобы было проще использовать линтеры и другие инструменты, а также чтобы дать читателям возможность с первого взгляда понять, какие мутации возможны в приложении: @@ -123,7 +123,7 @@ const store = new Vuex.Store({ Тем не менее, использовать константы для указания типов мутаций совершенно необязательно, хотя это и может оказаться полезным в крупных проектах. -### Мутации должны быть синхронными +## Мутации должны быть синхронными Нужно помнить одно важное правило: **обработчики мутаций обязаны быть синхронными**. Почему? Рассмотрим пример: @@ -139,7 +139,7 @@ mutations: { Теперь представьте, что вы отлаживаете приложение и смотрите в лог мутаций в инструментах разработчика. Для каждой залогированной мутации devtools должен сохранить слепки состояния приложения "до" и "после" её наступления. Однако, асинхронный коллбэк внутри приведённой выше мутации делает это невозможным: мутация-то уже записана, и у devtools нет никакой возможности знать, что далее будет вызван коллбэк, а, значит, и инициируемые им изменения становится, по сути дела, невозможно отследить. -### Вызов мутаций в компонентах +## Вызов мутаций в компонентах Мутации можно вызывать из кода компонентов, используя `this.$store.commit('xxx')`, или применяя вспомогательный метод `mapMutations`, который проксирует вызовы `store.commit` через методы компонентов (для этого требуется наличие корневой ссылки на хранилище `$store`): @@ -162,7 +162,7 @@ export default { }; ``` -### О действиях +## О действиях Привнесение асинхронности в мутации могло бы изрядно затруднить понимание логики программы. Например, если вызываются два метода, оба с асинхронными коллбэками, изменяющими состояние приложения — как предсказать, какой из коллбэков будет вызван первым? Именно поэтому концепции изменений и асинхронности рассматриваются по отдельности. Во Vuex **мутации — это синхронные транзакции**: diff --git a/docs/ru/guide/plugins.md b/docs/ru/guide/plugins.md index f4c808da0..b4584ad56 100644 --- a/docs/ru/guide/plugins.md +++ b/docs/ru/guide/plugins.md @@ -23,7 +23,7 @@ const store = new Vuex.Store({ }); ``` -### Вызов мутаций из плагинов +## Вызов мутаций из плагинов Плагинам не разрешается напрямую изменять состояние приложения — как и компоненты, они могут только вызывать изменения опосредованно, используя мутации. @@ -54,7 +54,7 @@ const store = new Vuex.Store({ }); ``` -### Снятие слепков состояния +## Снятие слепков состояния Иногда плагину может потребоваться "снять слепок" состояния приложения или сравнить состояния "до" и "после" мутации. Для этого используйте глубокое копирование объекта состояния: @@ -83,7 +83,7 @@ const store = new Vuex.Store({ Плагин будет использоваться по умолчанию. В production-окружении вам понадобится [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) для webpack, или [envify](https://github.com/hughsk/envify) для Browserify, чтобы изменить значение `process.env.NODE_ENV !== 'production'` на `false` в финальной сборке. -### Встроенный плагин логирования +## Встроенный плагин логирования > Если вы используете [vue-devtools](https://github.com/vuejs/vue-devtools), вам он скорее всего не понадобится @@ -140,11 +140,11 @@ const logger = createLogger({ Обратите внимание, что этот плагин делает слепки состояний, поэтому использовать его стоит только на этапе разработки. -#### Vuex до версии 3.5.0 +### Vuex до версии 3.5.0 До версии 3.5.0 функция `createLogger` экспортировалась по следующему пути `vuex/dist/logger`. -``` js +```js import createLogger from 'vuex/dist/logger' const store = new Vuex.Store({ plugins: [createLogger()] diff --git a/docs/ru/guide/state.md b/docs/ru/guide/state.md index 2abd3f26c..582bc13c8 100644 --- a/docs/ru/guide/state.md +++ b/docs/ru/guide/state.md @@ -1,6 +1,6 @@ # Состояние -### Единое дерево состояния +## Единое дерево состояния @@ -10,7 +10,7 @@ Vuex использует **единое дерево состояния** — Данные, которые хранятся во Vuex должны следовать тем же правилам, что и `data` в экземпляре Vue, т.е. объект состояния должен быть простым. **См. также:** [Vue#data](https://ru.vuejs.org/v2/api/#data). -### Использование состояния Vuex в компонентах Vue +## Использование состояния Vuex в компонентах Vue Итак, как использовать состояние хранилища в компонентах Vue? Поскольку хранилище Vuex реактивно, самый простой способ «получения» — просто вернуть часть состояния хранилища в [вычисляемом свойстве](https://ru.vuejs.org/v2/guide/computed.html): @@ -60,7 +60,7 @@ const Counter = { }; ``` -### Вспомогательная функция `mapState` +## Вспомогательная функция `mapState` @@ -97,7 +97,7 @@ computed: mapState([ ]); ``` -### Оператор распространения объектов +## Оператор распространения объектов Обратите внимание, `mapState` возвращает объект. Как же его использовать в сочетании с другими локальными вычисляемыми свойствами? Для этого обычно приходилось использовать вспомогательные утилиты для объединения нескольких объектов в один, который передавать в `computed`. Однако, с помощью [оператора распространения объектов](https://github.com/tc39/proposal-object-rest-spread) можно значительно упростить синтаксис: @@ -111,6 +111,6 @@ computed: { } ``` -### Компоненты всё ещё могут иметь локальное состояние +## Компоненты всё ещё могут иметь локальное состояние Использование Vuex **не означает, что нужно выносить всё состояние** в хранилище. Хотя перемещение большей части состояния во Vuex, сделает мутации более явными и удобными для отладки, это также может привести к многословности и ненужному усложнению логики. Если часть состояния относится только к одному компоненту, лучше оставить его в качестве локального состояния. Вы должны взвесить все компромиссы и принять решение, соответствующее потребностям приложения и вектора его развития. diff --git a/docs/ru/guide/strict.md b/docs/ru/guide/strict.md index 0ab880209..996a5f7dd 100644 --- a/docs/ru/guide/strict.md +++ b/docs/ru/guide/strict.md @@ -11,7 +11,7 @@ const store = new Vuex.Store({ В строгом режиме любая попытка внесения изменений в состояние Vuex, кроме мутаций, будет выбрасывать ошибку. Это гарантирует, что все мутации состояния будут явно отслеживаться через инструменты отладки. -### Разработка vs production +## Разработка vs production **Не используйте строгий режим в production!** Строгий режим запускает глубокое отслеживание за деревом состояния приложения в синхронном режиме для обнаружения несоответствующих мутаций, и это может быть затратным для производительности, когда совершается большое количество мутаций. Убедитесь, что выключили этот режим в production чтобы избежать ухудшения производительности. diff --git a/docs/ru/installation.md b/docs/ru/installation.md index 689704445..77d95185b 100644 --- a/docs/ru/installation.md +++ b/docs/ru/installation.md @@ -1,6 +1,6 @@ # Установка -### Скачивание напрямую / CDN +## Скачивание напрямую / CDN [https://unpkg.com/vuex](https://unpkg.com/vuex) @@ -17,30 +17,50 @@ ``` -### NPM +## NPM ```bash npm install vuex --save + +# При использовании Vue 3.0 + Vuex 4.0: +npm install vuex@next --save ``` -### Yarn +## Yarn ```bash yarn add vuex + +# При использовании Vue 3.0 + Vuex 4.0: +yarn add vuex@next --save ``` -При использовании системы сборки — явно установите Vuex с помощью команды `Vue.use()`: +При использовании системы сборки необходимо явно устанавливать как плагин: + +### Для Vue 2 ```js -import Vue from 'vue'; -import Vuex from 'vuex'; +import Vue from 'vue' +import Vuex from 'vuex' + +Vue.use(Vuex) +``` + +### Для Vue 3 + +```js +import { createApp } from 'vue' +import { createStore } from 'vuex' + +const app = createApp({ ... }) +const store = createStore({ ... }) -Vue.use(Vuex); +app.use(store) ``` При использовании глобальных тегов `