提交 359f7321 编写于 作者: fxy060608's avatar fxy060608

feat(mp): add vuex and devtools-api

上级 b76374b7
......@@ -105,7 +105,8 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) {
__UNI_WXS_API__: JSON.stringify(process.env.UNI_USING_WXS_API === 'true'),
__UNI_PROMISE_API__: JSON.stringify(process.env.UNI_USING_PROMISE_API === 'true'),
__VUE_OPTIONS_API__: JSON.stringify(process.env.UNI_USING_VUE3_OPTIONS_API === 'true'),
__VUE_CREATED_DEFERRED__: JSON.stringify(deferredCreated)
__VUE_CREATED_DEFERRED__: JSON.stringify(deferredCreated),
__VUE_PROD_DEVTOOLS__: JSON.stringify(false)
})
}
if (process.env.UNI_PLATFORM === 'h5') {
......@@ -139,4 +140,4 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) {
webpackConfig.plugins.delete('progress')
}
}
}
}
......@@ -2,6 +2,7 @@ const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const loaderUtils = require('loader-utils')
const moduleAlias = require('module-alias')
require('./error-reporting')
......@@ -16,8 +17,8 @@ if (process.env.UNI_INPUT_DIR && process.env.UNI_INPUT_DIR.indexOf('./') === 0)
process.env.UNI_INPUT_DIR = path.resolve(process.cwd(), process.env.UNI_INPUT_DIR)
}
process.env.UNI_INPUT_DIR = process.env.UNI_INPUT_DIR || path.resolve(process.cwd(), defaultInputDir)
const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson()
const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson()
// 小程序 vue3 标记
if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) {
......@@ -25,10 +26,10 @@ if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) {
process.env.UNI_USING_VUE3 = true
process.env.UNI_USING_VUE3_OPTIONS_API = true
}
}
}
// 初始化全局插件对象
global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init()
global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init()
const platformOptions = manifestJsonObj[process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM] || {}
// 插件校验环境
......@@ -374,8 +375,6 @@ if (process.env.NODE_ENV !== 'production') { // 运行模式性能提示
console.log(perfMsg)
}
const moduleAlias = require('module-alias')
// 将 template-compiler 指向修订后的版本
moduleAlias.addAlias('vue-template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/vue-template-compiler')
moduleAlias.addAlias('@megalo/template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/@megalo/template-compiler')
......
......@@ -181,6 +181,16 @@ module.exports = {
}
}
const alias = { // 仅 mp-weixin
'mpvue-page-factory': require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory')
}
if (process.env.UNI_USING_VUE3) {
alias.vuex = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vuex')
alias['@vue/devtools-api'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/devtools-api')
}
return {
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
entry () {
......@@ -197,10 +207,7 @@ module.exports = {
},
resolve: {
extensions: ['.nvue'],
alias: { // 仅 mp-weixin
'mpvue-page-factory': require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory')
}
alias
},
module: {
rules: [{
......
import { ComponentBounds, Hookable } from './hooks';
import { Context } from './context';
import { ComponentInstance, ComponentState, StateBase } from './component';
import { App } from './app';
import { ID } from './util';
export interface DevtoolsPluginApi {
on: Hookable<Context>;
notifyComponentUpdate(instance?: ComponentInstance): any;
addTimelineLayer(options: TimelineLayerOptions): any;
addTimelineEvent(options: TimelineEventOptions): any;
addInspector(options: CustomInspectorOptions): any;
sendInspectorTree(inspectorId: string): any;
sendInspectorState(inspectorId: string): any;
selectInspectorNode(inspectorId: string, nodeId: string): any;
getComponentBounds(instance: ComponentInstance): Promise<ComponentBounds>;
getComponentName(instance: ComponentInstance): Promise<string>;
getComponentInstances(app: App): Promise<ComponentInstance[]>;
highlightElement(instance: ComponentInstance): any;
unhighlightElement(): any;
}
export interface AppRecord {
id: number;
name: string;
instanceMap: Map<string, ComponentInstance>;
rootInstance: ComponentInstance;
}
export interface TimelineLayerOptions<TData = any, TMeta = any> {
id: string;
label: string;
color: number;
skipScreenshots?: boolean;
groupsOnly?: boolean;
ignoreNoDurationGroups?: boolean;
screenshotOverlayRender?: (event: TimelineEvent<TData, TMeta> & ScreenshotOverlayEvent, ctx: ScreenshotOverlayRenderContext) => ScreenshotOverlayRenderResult | Promise<ScreenshotOverlayRenderResult>;
}
export interface ScreenshotOverlayEvent {
layerId: string;
renderMeta: any;
}
export interface ScreenshotOverlayRenderContext<TData = any, TMeta = any> {
screenshot: ScreenshotData;
events: (TimelineEvent<TData, TMeta> & ScreenshotOverlayEvent)[];
index: number;
}
export declare type ScreenshotOverlayRenderResult = HTMLElement | string | false;
export interface ScreenshotData {
time: number;
}
export interface TimelineEventOptions {
layerId: string;
event: TimelineEvent;
all?: boolean;
}
export interface TimelineEvent<TData = any, TMeta = any> {
time: number;
data: TData;
logType?: 'default' | 'warning' | 'error';
meta?: TMeta;
groupId?: ID;
title?: string;
subtitle?: string;
}
export interface CustomInspectorOptions {
id: string;
label: string;
icon?: string;
treeFilterPlaceholder?: string;
stateFilterPlaceholder?: string;
noSelectionText?: string;
actions?: {
icon: string;
tooltip?: string;
action: () => void | Promise<void>;
}[];
}
export interface CustomInspectorNode {
id: string;
label: string;
children?: CustomInspectorNode[];
tags?: InspectorNodeTag[];
}
export interface InspectorNodeTag {
label: string;
textColor: number;
backgroundColor: number;
tooltip?: string;
}
export interface CustomInspectorState {
[key: string]: (StateBase | Omit<ComponentState, 'type'>)[];
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
import { InspectorNodeTag } from './api';
import { ID } from './util';
export declare type ComponentInstance = any;
export interface ComponentTreeNode {
uid: ID;
id: string;
name: string;
renderKey: string | number;
inactive: boolean;
isFragment: boolean;
hasChildren: boolean;
children: ComponentTreeNode[];
positionTop?: number;
consoleId?: string;
isRouterView?: boolean;
macthedRouteSegment?: string;
tags: InspectorNodeTag[];
meta?: any;
}
export interface InspectedComponentData {
id: string;
name: string;
file: string;
state: ComponentState[];
functional?: boolean;
}
export interface StateBase {
key: string;
value: any;
editable?: boolean;
objectType?: 'ref' | 'reactive' | 'computed' | 'other';
raw?: string;
}
export interface ComponentStateBase extends StateBase {
type: string;
}
export interface ComponentPropState extends ComponentStateBase {
meta?: {
type: string;
required: boolean;
/** Vue 1 only */
mode?: 'default' | 'sync' | 'once';
};
}
export declare type ComponentBuiltinCustomStateTypes = 'function' | 'map' | 'set' | 'reference' | 'component' | 'component-definition' | 'router' | 'store';
export interface ComponentCustomState extends ComponentStateBase {
value: CustomState;
}
export declare type CustomState = {
_custom: {
type: ComponentBuiltinCustomStateTypes | string;
display?: string;
tooltip?: string;
value?: any;
abstract?: boolean;
file?: string;
uid?: number;
readOnly?: boolean;
/** Configure immediate child fields */
fields?: {
abstract?: boolean;
};
id?: any;
actions?: {
icon: string;
tooltip?: string;
action: () => void | Promise<void>;
}[];
/** internal */
_reviveId?: number;
};
};
export declare type ComponentState = ComponentStateBase | ComponentPropState | ComponentCustomState;
export interface ComponentDevtoolsOptions {
hide?: boolean;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
import { AppRecord } from './api';
export interface Context {
currentTab: string;
currentAppRecord: AppRecord;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
import { ComponentTreeNode, InspectedComponentData, ComponentInstance, ComponentDevtoolsOptions } from './component';
import { App } from './app';
import { CustomInspectorNode, CustomInspectorState, TimelineEvent } from './api';
export declare const enum Hooks {
TRANSFORM_CALL = "transformCall",
GET_APP_RECORD_NAME = "getAppRecordName",
GET_APP_ROOT_INSTANCE = "getAppRootInstance",
REGISTER_APPLICATION = "registerApplication",
WALK_COMPONENT_TREE = "walkComponentTree",
VISIT_COMPONENT_TREE = "visitComponentTree",
WALK_COMPONENT_PARENTS = "walkComponentParents",
INSPECT_COMPONENT = "inspectComponent",
GET_COMPONENT_BOUNDS = "getComponentBounds",
GET_COMPONENT_NAME = "getComponentName",
GET_COMPONENT_INSTANCES = "getComponentInstances",
GET_ELEMENT_COMPONENT = "getElementComponent",
GET_COMPONENT_ROOT_ELEMENTS = "getComponentRootElements",
EDIT_COMPONENT_STATE = "editComponentState",
GET_COMPONENT_DEVTOOLS_OPTIONS = "getAppDevtoolsOptions",
GET_COMPONENT_RENDER_CODE = "getComponentRenderCode",
INSPECT_TIMELINE_EVENT = "inspectTimelineEvent",
TIMELINE_CLEARED = "timelineCleared",
GET_INSPECTOR_TREE = "getInspectorTree",
GET_INSPECTOR_STATE = "getInspectorState",
EDIT_INSPECTOR_STATE = "editInspectorState"
}
export interface ComponentBounds {
left: number;
top: number;
width: number;
height: number;
}
export declare type HookPayloads = {
[Hooks.TRANSFORM_CALL]: {
callName: string;
inArgs: any[];
outArgs: any[];
};
[Hooks.GET_APP_RECORD_NAME]: {
app: App;
name: string;
};
[Hooks.GET_APP_ROOT_INSTANCE]: {
app: App;
root: ComponentInstance;
};
[Hooks.REGISTER_APPLICATION]: {
app: App;
};
[Hooks.WALK_COMPONENT_TREE]: {
componentInstance: ComponentInstance;
componentTreeData: ComponentTreeNode[];
maxDepth: number;
filter: string;
};
[Hooks.VISIT_COMPONENT_TREE]: {
app: App;
componentInstance: ComponentInstance;
treeNode: ComponentTreeNode;
filter: string;
};
[Hooks.WALK_COMPONENT_PARENTS]: {
componentInstance: ComponentInstance;
parentInstances: ComponentInstance[];
};
[Hooks.INSPECT_COMPONENT]: {
app: App;
componentInstance: ComponentInstance;
instanceData: InspectedComponentData;
};
[Hooks.GET_COMPONENT_BOUNDS]: {
componentInstance: ComponentInstance;
bounds: ComponentBounds;
};
[Hooks.GET_COMPONENT_NAME]: {
componentInstance: ComponentInstance;
name: string;
};
[Hooks.GET_COMPONENT_INSTANCES]: {
app: App;
componentInstances: ComponentInstance[];
};
[Hooks.GET_ELEMENT_COMPONENT]: {
element: HTMLElement | any;
componentInstance: ComponentInstance;
};
[Hooks.GET_COMPONENT_ROOT_ELEMENTS]: {
componentInstance: ComponentInstance;
rootElements: (HTMLElement | any)[];
};
[Hooks.EDIT_COMPONENT_STATE]: {
app: App;
componentInstance: ComponentInstance;
path: string[];
type: string;
state: EditStatePayload;
set: (object: any, path: string | (string[]), value: any, cb?: (object: any, field: string, value: any) => void) => void;
};
[Hooks.GET_COMPONENT_DEVTOOLS_OPTIONS]: {
componentInstance: ComponentInstance;
options: ComponentDevtoolsOptions;
};
[Hooks.GET_COMPONENT_RENDER_CODE]: {
componentInstance: ComponentInstance;
code: string;
};
[Hooks.INSPECT_TIMELINE_EVENT]: {
app: App;
layerId: string;
event: TimelineEvent;
all?: boolean;
data: any;
};
[Hooks.TIMELINE_CLEARED]: Record<string, never>;
[Hooks.GET_INSPECTOR_TREE]: {
app: App;
inspectorId: string;
filter: string;
rootNodes: CustomInspectorNode[];
};
[Hooks.GET_INSPECTOR_STATE]: {
app: App;
inspectorId: string;
nodeId: string;
state: CustomInspectorState;
};
[Hooks.EDIT_INSPECTOR_STATE]: {
app: App;
inspectorId: string;
nodeId: string;
path: string[];
type: string;
state: EditStatePayload;
set: (object: any, path: string | (string[]), value: any, cb?: (object: any, field: string, value: any) => void) => void;
};
};
export declare type EditStatePayload = {
value: any;
newKey?: string | null;
remove?: undefined | false;
} | {
value?: undefined;
newKey?: undefined;
remove: true;
};
export declare type HookHandler<TPayload, TContext> = (payload: TPayload, ctx: TContext) => void | Promise<void>;
export interface Hookable<TContext> {
transformCall(handler: HookHandler<HookPayloads[Hooks.TRANSFORM_CALL], TContext>): any;
getAppRecordName(handler: HookHandler<HookPayloads[Hooks.GET_APP_RECORD_NAME], TContext>): any;
getAppRootInstance(handler: HookHandler<HookPayloads[Hooks.GET_APP_ROOT_INSTANCE], TContext>): any;
registerApplication(handler: HookHandler<HookPayloads[Hooks.REGISTER_APPLICATION], TContext>): any;
walkComponentTree(handler: HookHandler<HookPayloads[Hooks.WALK_COMPONENT_TREE], TContext>): any;
visitComponentTree(handler: HookHandler<HookPayloads[Hooks.VISIT_COMPONENT_TREE], TContext>): any;
walkComponentParents(handler: HookHandler<HookPayloads[Hooks.WALK_COMPONENT_PARENTS], TContext>): any;
inspectComponent(handler: HookHandler<HookPayloads[Hooks.INSPECT_COMPONENT], TContext>): any;
getComponentBounds(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_BOUNDS], TContext>): any;
getComponentName(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_NAME], TContext>): any;
getComponentInstances(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_INSTANCES], TContext>): any;
getElementComponent(handler: HookHandler<HookPayloads[Hooks.GET_ELEMENT_COMPONENT], TContext>): any;
getComponentRootElements(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_ROOT_ELEMENTS], TContext>): any;
editComponentState(handler: HookHandler<HookPayloads[Hooks.EDIT_COMPONENT_STATE], TContext>): any;
getComponentDevtoolsOptions(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_DEVTOOLS_OPTIONS], TContext>): any;
getComponentRenderCode(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_RENDER_CODE], TContext>): any;
inspectTimelineEvent(handler: HookHandler<HookPayloads[Hooks.INSPECT_TIMELINE_EVENT], TContext>): any;
timelineCleared(handler: HookHandler<HookPayloads[Hooks.TIMELINE_CLEARED], TContext>): any;
getInspectorTree(handler: HookHandler<HookPayloads[Hooks.GET_INSPECTOR_TREE], TContext>): any;
getInspectorState(handler: HookHandler<HookPayloads[Hooks.GET_INSPECTOR_STATE], TContext>): any;
editInspectorState(handler: HookHandler<HookPayloads[Hooks.EDIT_INSPECTOR_STATE], TContext>): any;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export * from './api';
export * from './app';
export * from './component';
export * from './context';
export * from './hooks';
export * from './util';
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./api"), exports);
__exportStar(require("./app"), exports);
__exportStar(require("./component"), exports);
__exportStar(require("./context"), exports);
__exportStar(require("./hooks"), exports);
__exportStar(require("./util"), exports);
export declare type ID = number | string;
export interface WithId {
id: ID;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export declare const HOOK_SETUP = "devtools-plugin:setup";
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HOOK_SETUP = void 0;
exports.HOOK_SETUP = 'devtools-plugin:setup';
import { PluginDescriptor, SetupFunction } from '.';
interface GlobalTarget {
__VUE_DEVTOOLS_PLUGINS__: Array<{
pluginDescriptor: PluginDescriptor;
setupFn: SetupFunction;
}>;
}
export declare function getDevtoolsGlobalHook(): any;
export declare function getTarget(): GlobalTarget;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTarget = exports.getDevtoolsGlobalHook = void 0;
function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
exports.getDevtoolsGlobalHook = getDevtoolsGlobalHook;
function getTarget() {
// @ts-ignore
return typeof navigator !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
}
exports.getTarget = getTarget;
import { DevtoolsPluginApi, App } from './api';
export * from './api';
export interface PluginDescriptor {
id: string;
label: string;
app: App;
packageName?: string;
homepage?: string;
componentStateTypes?: string[];
logo?: string;
disableAppScope?: boolean;
}
export declare type SetupFunction = (api: DevtoolsPluginApi) => void;
export declare function setupDevtoolsPlugin(pluginDescriptor: PluginDescriptor, setupFn: SetupFunction): void;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDevtoolsPlugin = void 0;
const env_1 = require("./env");
const const_1 = require("./const");
__exportStar(require("./api"), exports);
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const hook = env_1.getDevtoolsGlobalHook();
if (hook) {
hook.emit(const_1.HOOK_SETUP, pluginDescriptor, setupFn);
}
else {
const target = env_1.getTarget();
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
exports.setupDevtoolsPlugin = setupDevtoolsPlugin;
export * from './api';
export * from './app';
export * from './component';
export * from './context';
export * from './hooks';
export * from './util';
export function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
export function getTarget() {
// @ts-ignore
return typeof navigator !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
}
import { getTarget, getDevtoolsGlobalHook } from './env';
import { HOOK_SETUP } from './const';
export * from './api';
export function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const hook = getDevtoolsGlobalHook();
if (hook) {
hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
}
else {
const target = getTarget();
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
{
"name": "@vue/devtools-api",
"version": "6.0.0-beta.15",
"description": "Interact with the Vue devtools from the page",
"main": "lib/cjs/index.js",
"browser": "lib/esm/index.js",
"module": "lib/esm/index.js",
"types": "lib/cjs/index.d.ts",
"sideEffects": false,
"author": {
"name": "Guillaume Chau"
},
"files": [
"lib/esm",
"lib/cjs"
],
"license": "MIT",
"repository": {
"url": "https://github.com/vuejs/vue-devtools.git",
"type": "git",
"directory": "packages/api"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rimraf lib && yarn build:esm && yarn build:cjs",
"build:esm": "tsc --module es2015 --outDir lib/esm",
"build:cjs": "tsc --module commonjs --outDir lib/cjs -d",
"build:watch": "yarn tsc --module commonjs --outDir lib/cjs -d -w --sourceMap",
"ts": "yarn build:esm"
},
"devDependencies": {
"@types/node": "^13.9.1",
"@types/webpack-env": "^1.15.1",
"typescript": "^3.8.3"
}
}
\ No newline at end of file
此差异已折叠。
The MIT License (MIT)
Copyright (c) 2015-present Evan You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# Vuex
[![npm](https://img.shields.io/npm/v/vuex/next.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)
---
:fire: **HEADS UP!** You're currently looking at Vuex 4 branch. If you're looking for Vuex 3, [please check out `dev` branch](https://github.com/vuejs/vuex).
---
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://next.vuex.vuejs.org/)", or get started by looking into [full documentation](http://next.vuex.vuejs.org/).
## Documentation
To check out docs, visit [vuex.vuejs.org](https://next.vuex.vuejs.org/).
## Examples
You may find example applications built with Vuex under the `examples` directory.
Running the examples:
```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.
## License
[MIT](http://opensource.org/licenses/MIT)
Copyright (c) 2015-present Evan You
/*!
* vuex v4.0.2
* (c) 2021 Evan You
* @license MIT
*/
var Vuex = (function (t) { 'use strict'; var e = 'store'; function n () { return typeof navigator !== 'undefined' ? window : typeof global !== 'undefined' ? global : {} } function o (t, e) { var o = n().__VUE_DEVTOOLS_GLOBAL_HOOK__; if (o)o.emit('devtools-plugin:setup', t, e); else { var r = n(); (r.__VUE_DEVTOOLS_PLUGINS__ = r.__VUE_DEVTOOLS_PLUGINS__ || []).push({ pluginDescriptor: t, setupFn: e }) } } function r (t, e) { if (void 0 === e && (e = []), t === null || typeof t !== 'object') return t; var n; var o = (n = function (e) { return e.original === t }, e.filter(n)[0]); if (o) return o.copy; var i = Array.isArray(t) ? [] : {}; return e.push({ original: t, copy: i }), Object.keys(t).forEach(function (n) { i[n] = r(t[n], e) }), i } function i (t, e) { Object.keys(t).forEach(function (n) { return e(t[n], n) }) } function a (t) { return t !== null && typeof t === 'object' } function c (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 s (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), u(t, n, e) } function u (e, n, o) { var r = e._state; e.getters = {}, e._makeLocalGettersCache = Object.create(null); var a = e._wrappedGetters; var c = {}; i(a, function (t, n) { c[n] = (function (t, e) { return function () { return t(e) } }(t, e)), Object.defineProperty(e.getters, n, { get: function () { return c[n]() }, enumerable: !0 }) }), e._state = t.reactive({ data: n }), e.strict && (function (e) { t.watch(function () { return e._state.data }, function () {}, { deep: !0, flush: 'sync' }) }(e)), r && o && e._withCommit(function () { r.data = null }) } function l (t, e, n, o, r) { var i = !n.length; var a = t._modules.getNamespace(n); if (o.namespaced && (t._modulesNamespaceMap[a], t._modulesNamespaceMap[a] = o), !i && !r) { var c = p(e, n.slice(0, -1)); var s = n[n.length - 1]; t._withCommit(function () { c[s] = o.state }) } var u = o.context = (function (t, e, n) { var o = e === ''; var r = { dispatch: o ? t.dispatch : function (n, o, r) { var i = d(n, o, r); var a = i.payload; var c = i.options; var s = i.type; return c && c.root || (s = e + s), t.dispatch(s, a) }, commit: o ? t.commit : function (n, o, r) { var i = d(n, o, r); var a = i.payload; var c = i.options; var s = i.type; c && c.root || (s = e + s), t.commit(s, a, c) } }; return Object.defineProperties(r, { getters: { get: o ? function () { return t.getters } : function () { return f(t, e) } }, state: { get: function () { return p(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, u)) }), o.forEachAction(function (e, n) { var o = e.root ? n : a + n; var r = e.handler || e; !(function (t, e, n, o) { (t._actions[e] || (t._actions[e] = [])).push(function (e) { var r; var 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) && typeof r.then === 'function' || (i = Promise.resolve(i)), t._devtoolHook ? i.catch(function (e) { throw t._devtoolHook.emit('vuex:error', e), e }) : i }) }(t, o, r, u)) }), 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, u)) }), o.forEachChild(function (o, i) { l(t, e, n.concat(i), o, r) }) } function f (t, e) { if (!t._makeLocalGettersCache[e]) { var n = {}; var 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] } function p (t, e) { return e.reduce(function (t, e) { return t[e] }, t) } function d (t, e, n) { return a(t) && t.type && (n = e, e = t, t = t.type), { type: t, payload: e, options: n } } var h = 'vuex:mutations'; var v = 'vuex:actions'; var m = 'vuex'; var g = 0; function y (t, e) { o({ id: 'org.vuejs.vuex', app: t, label: 'Vuex', homepage: 'https://next.vuex.vuejs.org/', logo: 'https://vuejs.org/images/icons/favicon-96x96.png', packageName: 'vuex', componentStateTypes: ['vuex bindings'] }, function (n) { n.addTimelineLayer({ id: h, label: 'Vuex Mutations', color: _ }), n.addTimelineLayer({ id: v, label: 'Vuex Actions', color: _ }), n.addInspector({ id: m, label: 'Vuex', icon: 'storage', treeFilterPlaceholder: 'Filter stores...' }), n.on.getInspectorTree(function (n) { if (n.app === t && n.inspectorId === m) if (n.filter) { var o = []; O(o, e._modules.root, n.filter, ''), n.rootNodes = o } else n.rootNodes = [E(e._modules.root, '')] }), n.on.getInspectorState(function (n) { if (n.app === t && n.inspectorId === m) { var o = n.nodeId; f(e, o), n.state = (function (t, e, n) { e = n === 'root' ? e : e[n]; var o = Object.keys(e); var r = { state: Object.keys(t.state).map(function (e) { return { key: e, editable: !0, value: t.state[e] } }) }; if (o.length) { var i = (function (t) { var e = {}; return Object.keys(t).forEach(function (n) { var o = n.split('/'); if (o.length > 1) { var r = e; var i = o.pop(); o.forEach(function (t) { r[t] || (r[t] = { _custom: { value: {}, display: t, tooltip: 'Module', abstract: !0 } }), r = r[t]._custom.value }), r[i] = j(function () { return t[n] }) } else e[n] = j(function () { return t[n] }) }), e }(e)); r.getters = Object.keys(i).map(function (t) { return { key: t.endsWith('/') ? w(t) : t, editable: !1, value: j(function () { return i[t] }) } }) } return r }((r = e._modules, (a = (i = o).split('/').filter(function (t) { return t })).reduce(function (t, e, n) { var o = t[e]; if (!o) throw new Error('Missing module "' + e + '" for path "' + i + '".'); return n === a.length - 1 ? o : o._children }, i === 'root' ? r : r.root._children)), o === 'root' ? e.getters : e._makeLocalGettersCache, o)) } var r, i, a }), n.on.editInspectorState(function (n) { if (n.app === t && n.inspectorId === m) { var o = n.nodeId; var r = n.path; o !== 'root' && (r = o.split('/').filter(Boolean).concat(r)), e._withCommit(function () { n.set(e._state.data, r, n.state.value) }) } }), e.subscribe(function (t, e) { var o = {}; t.payload && (o.payload = t.payload), o.state = e, n.notifyComponentUpdate(), n.sendInspectorTree(m), n.sendInspectorState(m), n.addTimelineEvent({ layerId: h, event: { time: Date.now(), title: t.type, data: o } }) }), e.subscribeAction({ before: function (t, e) { var o = {}; t.payload && (o.payload = t.payload), t._id = g++, t._time = Date.now(), o.state = e, n.addTimelineEvent({ layerId: v, event: { time: t._time, title: t.type, groupId: t._id, subtitle: 'start', data: o } }) }, after: function (t, e) { var o = {}; var r = Date.now() - t._time; o.duration = { _custom: { type: 'duration', display: r + 'ms', tooltip: 'Action duration', value: r } }, t.payload && (o.payload = t.payload), o.state = e, n.addTimelineEvent({ layerId: v, event: { time: Date.now(), title: t.type, groupId: t._id, subtitle: 'end', data: o } }) } }) }) } var _ = 8702998; var b = { label: 'namespaced', textColor: 16777215, backgroundColor: 6710886 }; function w (t) { return t && t !== 'root' ? t.split('/').slice(-2, -1)[0] : 'Root' } function E (t, e) { return { id: e || 'root', label: w(e), tags: t.namespaced ? [b] : [], children: Object.keys(t._children).map(function (n) { return E(t._children[n], e + n + '/') }) } } function O (t, e, n, o) { o.includes(n) && t.push({ id: o || 'root', label: o.endsWith('/') ? o.slice(0, o.length - 1) : o || 'Root', tags: e.namespaced ? [b] : [] }), Object.keys(e._children).forEach(function (r) { O(t, e._children[r], n, o + r + '/') }) } function j (t) { try { return t() } catch (t) { return t } } var C = function (t, e) { this.runtime = e, this._children = Object.create(null), this._rawModule = t; var n = t.state; this.state = (typeof n === 'function' ? n() : n) || {} }; var M = { namespaced: { configurable: !0 } }; M.namespaced.get = function () { return !!this._rawModule.namespaced }, C.prototype.addChild = function (t, e) { this._children[t] = e }, C.prototype.removeChild = function (t) { delete this._children[t] }, C.prototype.getChild = function (t) { return this._children[t] }, C.prototype.hasChild = function (t) { return t in this._children }, C.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) }, C.prototype.forEachChild = function (t) { i(this._children, t) }, C.prototype.forEachGetter = function (t) { this._rawModule.getters && i(this._rawModule.getters, t) }, C.prototype.forEachAction = function (t) { this._rawModule.actions && i(this._rawModule.actions, t) }, C.prototype.forEachMutation = function (t) { this._rawModule.mutations && i(this._rawModule.mutations, t) }, Object.defineProperties(C.prototype, M); var k = function (t) { this.register([], t, !1) }; function x (t, e, n) { if (e.update(n), n.modules) for (var o in n.modules) { if (!e.getChild(o)) return; x(t.concat(o), e.getChild(o), n.modules[o]) } }k.prototype.get = function (t) { return t.reduce(function (t, e) { return t.getChild(e) }, this.root) }, k.prototype.getNamespace = function (t) { var e = this.root; return t.reduce(function (t, n) { return t + ((e = e.getChild(n)).namespaced ? n + '/' : '') }, '') }, k.prototype.update = function (t) { x([], this.root, t) }, k.prototype.register = function (t, e, n) { var o = this; void 0 === n && (n = !0); var r = new C(e, n); t.length === 0 ? this.root = r : this.get(t.slice(0, -1)).addChild(t[t.length - 1], r); e.modules && i(e.modules, function (e, r) { o.register(t.concat(r), e, n) }) }, k.prototype.unregister = function (t) { var e = this.get(t.slice(0, -1)); var n = t[t.length - 1]; var o = e.getChild(n); o && o.runtime && e.removeChild(n) }, k.prototype.isRegistered = function (t) { var e = this.get(t.slice(0, -1)); var n = t[t.length - 1]; return !!e && e.hasChild(n) }; var S = function (t) { var e = this; void 0 === t && (t = {}); var n = t.plugins; void 0 === n && (n = []); var o = t.strict; void 0 === o && (o = !1); var r = t.devtools; this._committing = !1, this._actions = Object.create(null), this._actionSubscribers = [], this._mutations = Object.create(null), this._wrappedGetters = Object.create(null), this._modules = new k(t), this._modulesNamespaceMap = Object.create(null), this._subscribers = [], this._makeLocalGettersCache = Object.create(null), this._devtools = r; var i = this; var a = this.dispatch; var c = this.commit; this.dispatch = function (t, e) { return a.call(i, t, e) }, this.commit = function (t, e, n) { return c.call(i, t, e, n) }, this.strict = o; var s = this._modules.root.state; l(this, s, [], this._modules.root), u(this, s), n.forEach(function (t) { return t(e) }) }; var A = { state: { configurable: !0 } }; S.prototype.install = function (t, n) { t.provide(n || e, this), t.config.globalProperties.$store = this, void 0 !== this._devtools && this._devtools && y(t, this) }, A.state.get = function () { return this._state.data }, A.state.set = function (t) {}, S.prototype.commit = function (t, e, n) { var o = this; var r = d(t, e, n); var i = r.type; var a = r.payload; var c = { type: i, payload: a }; var s = this._mutations[i]; s && (this._withCommit(function () { s.forEach(function (t) { t(a) }) }), this._subscribers.slice().forEach(function (t) { return t(c, o.state) })) }, S.prototype.dispatch = function (t, e) { var n = this; var o = d(t, e); var r = o.type; var i = o.payload; var a = { type: r, payload: i }; var c = this._actions[r]; if (c) { try { this._actionSubscribers.slice().filter(function (t) { return t.before }).forEach(function (t) { return t.before(a, n.state) }) } catch (t) {} var s = c.length > 1 ? Promise.all(c.map(function (t) { return t(i) })) : c[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(a, n.state) }) } catch (t) {}t(e) }, function (t) { try { n._actionSubscribers.filter(function (t) { return t.error }).forEach(function (e) { return e.error(a, n.state, t) }) } catch (t) {}e(t) }) }) } }, S.prototype.subscribe = function (t, e) { return c(t, this._subscribers, e) }, S.prototype.subscribeAction = function (t, e) { return c(typeof t === 'function' ? { before: t } : t, this._actionSubscribers, e) }, S.prototype.watch = function (e, n, o) { var r = this; return t.watch(function () { return e(r.state, r.getters) }, n, Object.assign({}, o)) }, S.prototype.replaceState = function (t) { var e = this; this._withCommit(function () { e._state.data = t }) }, S.prototype.registerModule = function (t, e, n) { void 0 === n && (n = {}), typeof t === 'string' && (t = [t]), this._modules.register(t, e), l(this, this.state, t, this._modules.get(t), n.preserveState), u(this, this.state) }, S.prototype.unregisterModule = function (t) { var e = this; typeof t === 'string' && (t = [t]), this._modules.unregister(t), this._withCommit(function () { delete p(e.state, t.slice(0, -1))[t[t.length - 1]] }), s(this) }, S.prototype.hasModule = function (t) { return typeof t === 'string' && (t = [t]), this._modules.isRegistered(t) }, S.prototype.hotUpdate = function (t) { this._modules.update(t), s(this, !0) }, S.prototype._withCommit = function (t) { var e = this._committing; this._committing = !0, t(), this._committing = e }, Object.defineProperties(S.prototype, A); var G = P(function (t, e) { var n = {}; return T(e).forEach(function (e) { var o = e.key; var r = e.val; n[o] = function () { var e = this.$store.state; var n = this.$store.getters; if (t) { var o = V(this.$store, 'mapState', t); if (!o) return; e = o.context.state, n = o.context.getters } return typeof r === 'function' ? r.call(this, e, n) : e[r] }, n[o].vuex = !0 }), n }); var I = P(function (t, e) { var n = {}; return T(e).forEach(function (e) { var o = e.key; var 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 = V(this.$store, 'mapMutations', t); if (!i) return; o = i.context.commit } return typeof r === 'function' ? r.apply(this, [o].concat(e)) : o.apply(this.$store, [r].concat(e)) } }), n }); var L = P(function (t, e) { var n = {}; return T(e).forEach(function (e) { var o = e.key; var r = e.val; r = t + r, n[o] = function () { if (!t || V(this.$store, 'mapGetters', t)) return this.$store.getters[r] }, n[o].vuex = !0 }), n }); var N = P(function (t, e) { var n = {}; return T(e).forEach(function (e) { var o = e.key; var 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 = V(this.$store, 'mapActions', t); if (!i) return; o = i.context.dispatch } return typeof r === 'function' ? r.apply(this, [o].concat(e)) : o.apply(this.$store, [r].concat(e)) } }), n }); function T (t) { return (function (t) { return Array.isArray(t) || a(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 P (t) { return function (e, n) { return typeof e !== 'string' ? (n = e, e = '') : e.charAt(e.length - 1) !== '/' && (e += '/'), t(e, n) } } function V (t, e, n) { return t._modulesNamespaceMap[n] } function $ (t, e, n) { var o = n ? t.groupCollapsed : t.group; try { o.call(t, e) } catch (n) { t.log(e) } } function D (t) { try { t.groupEnd() } catch (e) { t.log('—— log end ——') } } function F () { var t = new Date(); return ' @ ' + U(t.getHours(), 2) + ':' + U(t.getMinutes(), 2) + ':' + U(t.getSeconds(), 2) + '.' + U(t.getMilliseconds(), 3) } function U (t, e) { return n = '0', o = e - t.toString().length, new Array(o + 1).join(n) + t; var n, o } return { version: '4.0.2', Store: S, storeKey: e, createStore: function (t) { return new S(t) }, useStore: function (n) { return void 0 === n && (n = null), t.inject(n !== null ? n : e) }, mapState: G, mapMutations: I, mapGetters: L, mapActions: N, createNamespacedHelpers: function (t) { return { mapState: G.bind(null, t), mapGetters: L.bind(null, t), mapMutations: I.bind(null, t), mapActions: N.bind(null, t) } }, createLogger: function (t) { void 0 === t && (t = {}); var e = t.collapsed; void 0 === e && (e = !0); var n = t.filter; void 0 === n && (n = function (t, e, n) { return !0 }); var o = t.transformer; void 0 === o && (o = function (t) { return t }); var i = t.mutationTransformer; void 0 === i && (i = function (t) { return t }); var a = t.actionFilter; void 0 === a && (a = function (t, e) { return !0 }); var c = t.actionTransformer; void 0 === c && (c = function (t) { return t }); var s = t.logMutations; void 0 === s && (s = !0); var u = t.logActions; void 0 === u && (u = !0); var l = t.logger; return void 0 === l && (l = console), function (t) { var f = r(t.state); void 0 !== l && (s && t.subscribe(function (t, a) { var c = r(a); if (n(t, f, c)) { var s = F(); var u = i(t); var p = 'mutation ' + t.type + s; $(l, p, e), l.log('%c prev state', 'color: #9E9E9E; font-weight: bold', o(f)), l.log('%c mutation', 'color: #03A9F4; font-weight: bold', u), l.log('%c next state', 'color: #4CAF50; font-weight: bold', o(c)), D(l) }f = c }), u && t.subscribeAction(function (t, n) { if (a(t, n)) { var o = F(); var r = c(t); var i = 'action ' + t.type + o; $(l, i, e), l.log('%c action', 'color: #03A9F4; font-weight: bold', r), D(l) } })) } } } }(Vue))
import Vuex from '../dist/vuex.cjs.js'
const {
version,
Store,
storeKey,
createStore,
install,
useStore,
mapState,
mapMutations,
mapGetters,
mapActions,
createNamespacedHelpers,
createLogger
} = Vuex
export {
Vuex as default,
version,
Store,
storeKey,
createStore,
install,
useStore,
mapState,
mapMutations,
mapGetters,
mapActions,
createNamespacedHelpers,
createLogger
}
{
"name": "vuex",
"version": "4.0.2",
"description": "state management for Vue.js",
"main": "dist/vuex.cjs.js",
"exports": {
".": {
"module": "./dist/vuex.esm-bundler.js",
"require": "./dist/vuex.cjs.js",
"import": "./dist/vuex.mjs"
},
"./": "./"
},
"module": "dist/vuex.esm-bundler.js",
"browser": "dist/vuex.esm-browser.js",
"unpkg": "dist/vuex.global.js",
"jsdelivr": "dist/vuex.global.js",
"typings": "types/index.d.ts",
"sideEffects": false,
"files": [
"dist",
"types/index.d.ts",
"types/helpers.d.ts",
"types/logger.d.ts",
"types/vue.d.ts"
],
"scripts": {
"dev": "node examples/server.js",
"build": "node scripts/build.js",
"lint": "eslint src test",
"test": "npm run lint && npm run build && npm run test:types && npm run test:unit && npm run test:ssr && npm run test:e2e && npm run test:esm",
"test:unit": "jest --testPathIgnorePatterns test/e2e",
"test:e2e": "start-server-and-test dev http://localhost:8080 \"jest --testPathIgnorePatterns test/unit\"",
"test:ssr": "cross-env VUE_ENV=server jest --testPathIgnorePatterns test/e2e",
"test:types": "tsc -p types/test",
"test:esm": "node test/esm/esm-test.js",
"coverage": "jest --testPathIgnorePatterns test/e2e --coverage",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"release": "node scripts/release.js",
"docs": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:serve": "yarn docs:build && vitepress serve docs"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vuex.git"
},
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vuex/issues"
},
"homepage": "https://github.com/vuejs/vuex#readme",
"peerDependencies": {
"vue": "^3.0.2"
},
"dependencies": {
"@vue/devtools-api": "^6.0.0-beta.11"
},
"devDependencies": {
"@babel/core": "^7.14.3",
"@babel/preset-env": "^7.14.2",
"@rollup/plugin-buble": "^0.21.3",
"@rollup/plugin-commonjs": "^19.0.0",
"@rollup/plugin-node-resolve": "^13.0.0",
"@rollup/plugin-replace": "^2.4.2",
"@types/node": "^15.6.0",
"@vue/compiler-sfc": "^3.0.11",
"babel-jest": "^26.6.3",
"babel-loader": "^8.2.2",
"brotli": "^1.3.2",
"chalk": "^4.1.1",
"conventional-changelog-cli": "^2.1.1",
"cross-env": "^7.0.3",
"css-loader": "^2.1.0",
"enquirer": "^2.3.5",
"eslint": "^7.27.0",
"eslint-plugin-vue-libs": "^4.0.0",
"execa": "^5.0.0",
"express": "^4.17.1",
"fs-extra": "^10.0.0",
"jest": "^26.6.3",
"puppeteer": "^9.1.1",
"regenerator-runtime": "^0.13.5",
"rollup": "^2.49.0",
"rollup-plugin-terser": "^7.0.2",
"semver": "^7.3.5",
"start-server-and-test": "^1.12.3",
"todomvc-app-css": "^2.4.1",
"typescript": "^4.2.4",
"vitepress": "^0.11.5",
"vue": "^3.0.11",
"vue-loader": "^16.2.0",
"vue-style-loader": "^4.1.3",
"webpack": "^4.43.0",
"webpack-dev-middleware": "^3.7.2",
"webpack-hot-middleware": "^2.25.0"
}
}
import { ComponentPublicInstance } from 'vue';
import { Dispatch, Commit } from './index';
type Computed = () => any;
type InlineComputed<T extends Function> = T extends (...args: any[]) => infer R ? () => R : never
type MutationMethod = (...args: any[]) => void;
type ActionMethod = (...args: any[]) => Promise<any>;
type InlineMethod<T extends (fn: any, ...args: any[]) => any> = T extends (fn: any, ...args: infer Args) => infer R ? (...args: Args) => R : never
type CustomVue = ComponentPublicInstance & Record<string, any>;
interface Mapper<R> {
<Key extends string>(map: Key[]): { [K in Key]: R };
<Map extends Record<string, string>>(map: Map): { [K in keyof Map]: R };
}
interface MapperWithNamespace<R> {
<Key extends string>(namespace: string, map: Key[]): { [K in Key]: R };
<Map extends Record<string, string>>(namespace: string, map: Map): { [K in keyof Map]: R };
}
interface MapperForState {
<S, Map extends Record<string, (this: CustomVue, state: S, getters: any) => any> = {}>(
map: Map
): { [K in keyof Map]: InlineComputed<Map[K]> };
}
interface MapperForStateWithNamespace {
<S, Map extends Record<string, (this: CustomVue, state: S, getters: any) => any> = {}>(
namespace: string,
map: Map
): { [K in keyof Map]: InlineComputed<Map[K]> };
}
interface MapperForAction {
<Map extends Record<string, (this: CustomVue, dispatch: Dispatch, ...args: any[]) => any>>(
map: Map
): { [K in keyof Map]: InlineMethod<Map[K]> };
}
interface MapperForActionWithNamespace {
<Map extends Record<string, (this: CustomVue, dispatch: Dispatch, ...args: any[]) => any>>(
namespace: string,
map: Map
): { [K in keyof Map]: InlineMethod<Map[K]> };
}
interface MapperForMutation {
<Map extends Record<string, (this: CustomVue, commit: Commit, ...args: any[]) => any>>(
map: Map
): { [K in keyof Map]: InlineMethod<Map[K]> };
}
interface MapperForMutationWithNamespace {
<Map extends Record<string, (this: CustomVue, commit: Commit, ...args: any[]) => any>>(
namespace: string,
map: Map
): { [K in keyof Map]: InlineMethod<Map[K]> };
}
interface NamespacedMappers {
mapState: Mapper<Computed> & MapperForState;
mapMutations: Mapper<MutationMethod> & MapperForMutation;
mapGetters: Mapper<Computed>;
mapActions: Mapper<ActionMethod> & MapperForAction;
}
export declare const mapState: Mapper<Computed>
& MapperWithNamespace<Computed>
& MapperForState
& MapperForStateWithNamespace;
export declare const mapMutations: Mapper<MutationMethod>
& MapperWithNamespace<MutationMethod>
& MapperForMutation
& MapperForMutationWithNamespace;
export declare const mapGetters: Mapper<Computed>
& MapperWithNamespace<Computed>;
export declare const mapActions: Mapper<ActionMethod>
& MapperWithNamespace<ActionMethod>
& MapperForAction
& MapperForActionWithNamespace;
export declare function createNamespacedHelpers(namespace: string): NamespacedMappers;
import { App, WatchOptions, InjectionKey } from "vue";
// augment typings of Vue.js
import "./vue";
import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from "./helpers";
import { createLogger } from "./logger";
export * from "./helpers";
export * from "./logger";
export declare class Store<S> {
constructor(options: StoreOptions<S>);
readonly state: S;
readonly getters: any;
install(app: App, injectKey?: InjectionKey<Store<any>> | string): void;
replaceState(state: S): void;
dispatch: Dispatch;
commit: Commit;
subscribe<P extends MutationPayload>(fn: (mutation: P, state: S) => any, options?: SubscribeOptions): () => void;
subscribeAction<P extends ActionPayload>(fn: SubscribeActionOptions<P, S>, options?: SubscribeOptions): () => void;
watch<T>(getter: (state: S, getters: any) => T, cb: (value: T, oldValue: T) => void, options?: WatchOptions): () => void;
registerModule<T>(path: string, module: Module<T, S>, options?: ModuleOptions): void;
registerModule<T>(path: string[], module: Module<T, S>, options?: ModuleOptions): void;
unregisterModule(path: string): void;
unregisterModule(path: string[]): void;
hasModule(path: string): boolean;
hasModule(path: string[]): boolean;
hotUpdate(options: {
actions?: ActionTree<S, S>;
mutations?: MutationTree<S>;
getters?: GetterTree<S, S>;
modules?: ModuleTree<S>;
}): void;
}
export const storeKey: string;
export function createStore<S>(options: StoreOptions<S>): Store<S>;
export function useStore<S = any>(injectKey?: InjectionKey<Store<S>> | string): Store<S>;
export interface Dispatch {
(type: string, payload?: any, options?: DispatchOptions): Promise<any>;
<P extends Payload>(payloadWithType: P, options?: DispatchOptions): Promise<any>;
}
export interface Commit {
(type: string, payload?: any, options?: CommitOptions): void;
<P extends Payload>(payloadWithType: P, options?: CommitOptions): void;
}
export interface ActionContext<S, R> {
dispatch: Dispatch;
commit: Commit;
state: S;
getters: any;
rootState: R;
rootGetters: any;
}
export interface Payload {
type: string;
}
export interface MutationPayload extends Payload {
payload: any;
}
export interface ActionPayload extends Payload {
payload: any;
}
export interface SubscribeOptions {
prepend?: boolean
}
export type ActionSubscriber<P, S> = (action: P, state: S) => any;
export type ActionErrorSubscriber<P, S> = (action: P, state: S, error: Error) => any;
export interface ActionSubscribersObject<P, S> {
before?: ActionSubscriber<P, S>;
after?: ActionSubscriber<P, S>;
error?: ActionErrorSubscriber<P, S>;
}
export type SubscribeActionOptions<P, S> = ActionSubscriber<P, S> | ActionSubscribersObject<P, S>;
export interface DispatchOptions {
root?: boolean;
}
export interface CommitOptions {
silent?: boolean;
root?: boolean;
}
export interface StoreOptions<S> {
state?: S | (() => S);
getters?: GetterTree<S, S>;
actions?: ActionTree<S, S>;
mutations?: MutationTree<S>;
modules?: ModuleTree<S>;
plugins?: Plugin<S>[];
strict?: boolean;
devtools?: boolean;
}
export type ActionHandler<S, R> = (this: Store<R>, injectee: ActionContext<S, R>, payload?: any) => any;
export interface ActionObject<S, R> {
root?: boolean;
handler: ActionHandler<S, R>;
}
export type Getter<S, R> = (state: S, getters: any, rootState: R, rootGetters: any) => any;
export type Action<S, R> = ActionHandler<S, R> | ActionObject<S, R>;
export type Mutation<S> = (state: S, payload?: any) => any;
export type Plugin<S> = (store: Store<S>) => any;
export interface Module<S, R> {
namespaced?: boolean;
state?: S | (() => S);
getters?: GetterTree<S, R>;
actions?: ActionTree<S, R>;
mutations?: MutationTree<S>;
modules?: ModuleTree<R>;
}
export interface ModuleOptions {
preserveState?: boolean;
}
export interface GetterTree<S, R> {
[key: string]: Getter<S, R>;
}
export interface ActionTree<S, R> {
[key: string]: Action<S, R>;
}
export interface MutationTree<S> {
[key: string]: Mutation<S>;
}
export interface ModuleTree<R> {
[key: string]: Module<any, R>;
}
declare const _default: {
Store: typeof Store;
mapState: typeof mapState,
mapMutations: typeof mapMutations,
mapGetters: typeof mapGetters,
mapActions: typeof mapActions,
createNamespacedHelpers: typeof createNamespacedHelpers,
createLogger: typeof createLogger
};
export default _default;
import { Payload, Plugin } from "./index";
interface Logger extends Partial<Pick<Console, 'groupCollapsed' | 'group' | 'groupEnd'>> {
log(message: string, color: string, payload: any): void;
log(message: string): void;
}
export interface LoggerOption<S> {
collapsed?: boolean;
filter?: <P extends Payload>(mutation: P, stateBefore: S, stateAfter: S) => boolean;
transformer?: (state: S) => any;
mutationTransformer?: <P extends Payload>(mutation: P) => any;
actionFilter?: <P extends Payload>(action: P, state: S) => boolean;
actionTransformer?: <P extends Payload>(action: P) => any;
logMutations?: boolean;
logActions?: boolean;
logger?: Logger;
}
export function createLogger<S>(option?: LoggerOption<S>): Plugin<S>;
/**
* Extends interfaces in Vue.js
*/
import { ComponentCustomOptions } from "vue";
import { Store } from "./index";
declare module "@vue/runtime-core" {
interface ComponentCustomOptions {
store?: Store<any>;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册