├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .gitignore ├── .postcssrc.js ├── README.md ├── build ├── build.js ├── check-versions.js ├── dev-client.js ├── dev-server.js ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js └── webpack.prod.conf.js ├── config ├── dev.env.js ├── index.js └── prod.env.js ├── debug.log ├── index.html ├── package-lock.json ├── package.json ├── src ├── App.vue ├── assets │ ├── css │ │ └── select.css │ ├── images │ │ ├── select_bg.png │ │ └── select_search.png │ └── logo.png ├── components │ ├── about.vue │ ├── charts.vue │ └── home.vue ├── main.js ├── router │ └── index.js ├── shared │ └── actions.js └── store │ ├── actions.js │ ├── commoms │ ├── about.js │ └── index.js │ ├── getters.js │ ├── index.js │ └── mutations.js └── static └── .gitkeep /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { "modules": false }], 4 | "stage-2" 5 | ], 6 | "plugins": ["transform-runtime"], 7 | "comments": false, 8 | "env": { 9 | "test": { 10 | "presets": ["env", "stage-2"], 11 | "plugins": [ "istanbul" ] 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | config/*.js 3 | src/assets 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parserOptions: { 4 | parser: 'babel-eslint', 5 | sourceType: 'module' 6 | }, 7 | env: { 8 | browser: true, 9 | node: true, 10 | es6: true, 11 | }, 12 | extends: ['plugin:vue/recommended', 'eslint:recommended'], // 最严格模式,会在命令窗口打印错误提示 13 | // extends: ['plugin:vue/essential', 'eslint:recommended'], 14 | 15 | // add your custom rules here 16 | // it is base on https://github.com/vuejs/eslint-config-vue 17 | // 中文文档 https://cn.eslint.org/docs/rules/ 18 | rules: { 19 | "vue/max-attributes-per-line": [2, { 20 | "singleline": 10, 21 | "multiline": { 22 | "max": 1, 23 | "allowFirstLine": false 24 | } 25 | }], 26 | "vue/name-property-casing": ["error", "PascalCase"], 27 | 'accessor-pairs': 2, // 强制 getter 和 setter 在对象中成对出现 28 | 'arrow-spacing': [2, { 29 | 'before': true, 30 | 'after': true 31 | }], // 强制箭头函数的箭头前后使用一致的空格 32 | 'block-spacing': [2, 'always'], // 禁止或强制在代码块中开括号前和闭括号后有空格 33 | 'brace-style': [2, '1tbs', { 34 | 'allowSingleLine': true 35 | }], // 强制在代码块中使用一致的大括号风格 36 | 'camelcase': [0, { 37 | 'properties': 'always' 38 | }], // 强制使用骆驼拼写法命名约定 39 | 'comma-dangle': [2, 'never'], // 要求或禁止末尾逗号 40 | 'comma-spacing': [2, { 41 | 'before': false, 42 | 'after': true 43 | }], // 强制在逗号前后使用一致的空格 44 | 'comma-style': [2, 'last'], // 强制使用一致的逗号风格 45 | 'constructor-super': 2, // 要求在构造函数中有 super() 的调用 46 | 'curly': [2, 'multi-line'], // 强制所有控制语句使用一致的括号风格 47 | 'dot-location': [2, 'property'], // 强制在点号之前和之后一致的换行 48 | 'eol-last': 2, // 要求或禁止文件末尾存在空行 49 | 'eqeqeq': [2, 'allow-null'], // 要求使用 === 和 !== 50 | 'generator-star-spacing': [2, { 51 | 'before': true, 52 | 'after': true 53 | }], // 强制 generator 函数中 * 号周围使用一致的空格 54 | 'handle-callback-err': [2, '^(err|error)$'], // 要求回调函数中有容错处理 55 | 'indent': [2, 2, { 56 | 'SwitchCase': 1 57 | }], // 强制使用一致的缩进 58 | 'jsx-quotes': [2, 'prefer-single'], // 强制在 JSX 属性中一致地使用双引号或单引号 59 | 'key-spacing': [2, { 60 | 'beforeColon': false, 61 | 'afterColon': true 62 | }], // 强制在对象字面量的属性中键和值之间使用一致的间距 63 | 'keyword-spacing': [2, { 64 | 'before': true, 65 | 'after': true 66 | }], // 强制在关键字前后使用一致的空格 67 | 'new-cap': [2, { 68 | 'newIsCap': true, 69 | 'capIsNew': false 70 | }], // 要求构造函数首字母大写 71 | 'new-parens': 2, // 要求调用无参构造函数时有圆括号 72 | 'no-array-constructor': 2, // 禁用 Array 构造函数 73 | 'no-caller': 2, // 禁用 arguments.caller 或 arguments.callee 74 | 'no-console': 'off', // 禁用 console 75 | 'no-class-assign': 2, // 禁止修改类声明的变量 76 | 'no-cond-assign': 2, // 禁止条件表达式中出现赋值操作符 77 | 'no-const-assign': 2, // 禁止修改 const 声明的变量 78 | 'no-control-regex': 2, // 禁止在正则表达式中使用控制字符 79 | 'no-delete-var': 2, // 禁止删除变量 80 | 'no-dupe-args': 2, // 禁止 function 定义中出现重名参数 81 | 'no-dupe-class-members': 2, // 禁止类成员中出现重复的名称 82 | 'no-dupe-keys': 2, // 禁止对象字面量中出现重复的 key 83 | 'no-duplicate-case': 2, // 禁止出现重复的 case 标签 84 | 'no-empty-character-class': 2, // 禁止在正则表达式中使用空字符集 85 | 'no-empty-pattern': 2, // 禁止使用空解构模式 86 | 'no-eval': 2, // 禁用 eval() 87 | 'no-ex-assign': 2, // 禁止对 catch 子句的参数重新赋值 88 | 'no-extend-native': 2, // 禁止扩展原生类型 89 | 'no-extra-bind': 2, // 禁止不必要的 .bind() 调用 90 | 'no-extra-boolean-cast': 2, // 禁止不必要的布尔转换 91 | 'no-extra-parens': [2, 'functions'], // 禁止不必要的括号 92 | 'no-fallthrough': 2, // 禁止 case 语句落空 93 | 'no-floating-decimal': 2, // 禁止数字字面量中使用前导和末尾小数点 94 | 'no-func-assign': 2, // 禁止对 function 声明重新赋值 95 | 'no-implied-eval': 2, // 禁止使用类似 eval() 的方法 96 | 'no-inner-declarations': [2, 'functions'], // 禁止在嵌套的块中出现变量声明或 function 声明 97 | 'no-invalid-regexp': 2, // 禁止 RegExp 构造函数中存在无效的正则表达式字符串 98 | 'no-irregular-whitespace': 2, // 禁止在字符串和注释之外不规则的空白 99 | 'no-iterator': 2, // 禁用 __iterator__ 属性 100 | 'no-label-var': 2, // 不允许标签与变量同名 101 | 'no-labels': [2, { 102 | 'allowLoop': false, 103 | 'allowSwitch': false 104 | }], // 禁用标签语句 105 | 'no-lone-blocks': 2, // 禁用不必要的嵌套块 106 | 'no-mixed-spaces-and-tabs': 2, // 禁止空格和 tab 的混合缩进 107 | 'no-multi-spaces': 2, // 禁止使用多个空格 108 | 'no-multi-str': 2, // 禁止使用多行字符串 109 | 'no-multiple-empty-lines': [2, { 110 | 'max': 3, 111 | "maxEOF": 3, 112 | "maxBOF": 3, 113 | }], // 禁止出现多行空行(此处设置最多出现连续3个空行) 114 | 'no-global-assign': 2, // 禁止对原生对象或只读的全局对象进行赋值,原no-native-reassign已被此替换 115 | 'no-unsafe-negation': 2, // 禁止对关系运算符的左操作数使用否定操作符,原no-negated-in-lhs已被此替换 116 | 'no-new-object': 2, // 禁用 Object 的构造函数 117 | 'no-new-require': 2, // 禁止调用 require 时使用 new 操作符 118 | 'no-new-symbol': 2, // 禁止 Symbolnew 操作符和 new 一起使用 119 | 'no-new-wrappers': 2, // 禁止对 String,Number 和 Boolean 使用 new 操作符 120 | 'no-obj-calls': 2, // 禁止把全局对象作为函数调用 121 | 'no-octal': 2, // 禁用八进制字面量 122 | 'no-octal-escape': 2, // 禁止在字符串中使用八进制转义序列 123 | 'no-path-concat': 2, // 禁止对 __dirname 和 __filename 进行字符串连接 124 | 'no-proto': 2, // 禁用 __proto__ 属性 125 | 'no-redeclare': 2, // 禁止多次声明同一变量 126 | 'no-regex-spaces': 2, // 127 | 'no-return-assign': [2, 'except-parens'], // 禁止在 return 语句中使用赋值语句 128 | 'no-self-assign': 2, // 禁止自我赋值 129 | 'no-self-compare': 2, // 禁止自身比较 130 | 'no-sequences': 2, // 禁用逗号操作符 131 | 'no-shadow-restricted-names': 2, // 禁止将标识符定义为受限的名字 132 | 'func-call-spacing': 2, // 要求或禁止在函数标识符和其调用之间有空格,原no-spaced-func已被此替换 133 | 'no-sparse-arrays': 2, // 禁用稀疏数组 134 | 'no-this-before-super': 2, // 禁止在构造函数中,在调用 super() 之前使用 this 或 super 135 | 'no-throw-literal': 2, // 禁止抛出异常字面量 136 | 'no-trailing-spaces': 1, // 禁用行尾空格 137 | 'no-undef': 2, // 禁用未声明的变量,除非它们在 /*global */ 注释中被提到 138 | 'no-undef-init': 2, // 禁止将变量初始化为 undefined 139 | 'no-unexpected-multiline': 2, // 禁止出现令人困惑的多行表达式 140 | 'no-unmodified-loop-condition': 2, // 禁用一成不变的循环条件 141 | 'no-unneeded-ternary': [2, { 142 | 'defaultAssignment': false 143 | }], // 禁止可以在有更简单的可替代的表达式时使用三元操作符 144 | 'no-unreachable': 2, // 禁止在return、throw、continue 和 break 语句之后出现不可达代码 145 | 'no-unsafe-finally': 2, // 禁止在 finally 语句块中出现控制流语句 146 | 'no-unused-vars': [2, { 147 | 'vars': 'all', 148 | 'args': 'none' 149 | }], // 禁止出现未使用过的变量 150 | 'no-useless-call': 2, // 禁止不必要的 .call() 和 .apply() 151 | 'no-useless-computed-key': 2, // 禁止在对象中使用不必要的计算属性 152 | 'no-useless-constructor': 2, // 禁用不必要的构造函数 153 | 'no-useless-escape': 0, // 禁用不必要的转义字符 154 | 'no-whitespace-before-property': 2, // 禁止属性前有空白 155 | 'no-with': 2, // 禁用 with 语句 156 | 'one-var': [2, { 157 | 'initialized': 'never' 158 | }], // 强制函数中的变量要么一起声明要么分开声明 159 | 'operator-linebreak': [2, 'after', { 160 | 'overrides': { 161 | '?': 'before', 162 | ':': 'before' 163 | } 164 | }], // 强制操作符使用一致的换行符 165 | 'padded-blocks': [0, 'never'], // 要求或禁止块内填充 166 | 'quotes': [2, 'single', { 167 | 'avoidEscape': true, 168 | 'allowTemplateLiterals': true 169 | }], // 强制使用一致的反勾号、双引号或单引号 170 | // 'semi': [2, 'never'], // 要求或禁止使用分号代替 ASI,分号设置:never 从不出现分号,always 必须分号结尾 171 | 'semi': [0], 172 | 'semi-spacing': [2, { 173 | 'before': false, 174 | 'after': true 175 | }], // 强制分号之前和之后使用一致的空格 176 | 'space-before-blocks': [2, 'always'], // 强制在块之前使用一致的空格 177 | 'space-before-function-paren': [2, 'never'], // 强制在 function的左括号之前使用一致的空格 178 | 'space-in-parens': [2, 'never'], // 强制在圆括号内使用一致的空格 179 | 'space-infix-ops': 2, // 要求操作符周围有空格 180 | 'space-unary-ops': [2, { 181 | 'words': true, 182 | 'nonwords': false 183 | }], // 强制在一元操作符前后使用一致的空格 184 | 'spaced-comment': [2, 'always', { 185 | 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ','] 186 | }], // 强制在注释中 // 或 /* 使用一致的空格 187 | 'template-curly-spacing': [2, 'never'], // 要求或禁止模板字符串中的嵌入表达式周围空格的使用 188 | 'use-isnan': 2, // 要求使用 isNaN() 检查 NaN 189 | 'valid-typeof': 2, // 强制 typeof 表达式与有效的字符串进行比较 190 | 'wrap-iife': [2, 'any'], // 要求 IIFE 使用括号括起来 191 | 'yield-star-spacing': [2, 'both'], // 强制在 yield* 表达式中 * 周围使用空格 192 | 'yoda': [2, 'never'], // 要求或禁止 “Yoda” 条件 193 | 'prefer-const': 2, // 要求使用 const 声明那些声明后不再被修改的变量 194 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, // 禁用 debugger 195 | 'object-curly-spacing': [2, 'always', { 196 | objectsInObjects: false 197 | }], // 强制在大括号中使用一致的空格 198 | 'array-bracket-spacing': [2, 'never'] // 强制数组方括号中使用一致的空格 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.css linguist-language=vue 2 | *.less linguist-language=vue 3 | *.js linguist-language=vue 4 | *.html linguist-language=vue 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | -------------------------------------------------------------------------------- /.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserlist" field in package.json 6 | "autoprefixer": {} 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | vuejs 4 | 5 | 6 | router 7 | 8 | 9 | axios 10 | 11 | 12 | vuex 13 | 14 |

15 | 16 | # vuex-examplate 17 | 18 | > 有关vuex的最佳实践,包括基本vuex用法、异步action,以及更高级的辅助函数mapState、mapGetters、mapActions,modules模块分割,命名空间,全局和局部的state数据修改进行函数封装,你想到的没想到的,我都尝试过。 19 | 20 | ## Build Setup 21 | 22 | ``` bash 23 | # install dependencies 24 | npm install 25 | 26 | # serve with hot reload at localhost:8080 27 | npm run dev 28 | 29 | # build for production with minification 30 | npm run build 31 | 32 | # build for production and view the bundle analyzer report 33 | npm run build --report 34 | ``` 35 | 36 | -------------------------------------------------------------------------------- /build/build.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | process.env.NODE_ENV = 'production' 4 | 5 | var ora = require('ora') 6 | var rm = require('rimraf') 7 | var path = require('path') 8 | var chalk = require('chalk') 9 | var webpack = require('webpack') 10 | var config = require('../config') 11 | var webpackConfig = require('./webpack.prod.conf') 12 | 13 | var spinner = ora('building for production...') 14 | spinner.start() 15 | 16 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 17 | if (err) throw err 18 | webpack(webpackConfig, function (err, stats) { 19 | spinner.stop() 20 | if (err) throw err 21 | process.stdout.write(stats.toString({ 22 | colors: true, 23 | modules: false, 24 | children: false, 25 | chunks: false, 26 | chunkModules: false 27 | }) + '\n\n') 28 | 29 | console.log(chalk.cyan(' Build complete.\n')) 30 | console.log(chalk.yellow( 31 | ' Tip: built files are meant to be served over an HTTP server.\n' + 32 | ' Opening index.html over file:// won\'t work.\n' 33 | )) 34 | }) 35 | }) 36 | -------------------------------------------------------------------------------- /build/check-versions.js: -------------------------------------------------------------------------------- 1 | var chalk = require('chalk') 2 | var semver = require('semver') 3 | var packageConfig = require('../package.json') 4 | var shell = require('shelljs') 5 | function exec (cmd) { 6 | return require('child_process').execSync(cmd).toString().trim() 7 | } 8 | 9 | var versionRequirements = [ 10 | { 11 | name: 'node', 12 | currentVersion: semver.clean(process.version), 13 | versionRequirement: packageConfig.engines.node 14 | }, 15 | ] 16 | 17 | if (shell.which('npm')) { 18 | versionRequirements.push({ 19 | name: 'npm', 20 | currentVersion: exec('npm --version'), 21 | versionRequirement: packageConfig.engines.npm 22 | }) 23 | } 24 | 25 | module.exports = function () { 26 | var warnings = [] 27 | for (var i = 0; i < versionRequirements.length; i++) { 28 | var mod = versionRequirements[i] 29 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 30 | warnings.push(mod.name + ': ' + 31 | chalk.red(mod.currentVersion) + ' should be ' + 32 | chalk.green(mod.versionRequirement) 33 | ) 34 | } 35 | } 36 | 37 | if (warnings.length) { 38 | console.log('') 39 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 40 | console.log() 41 | for (var i = 0; i < warnings.length; i++) { 42 | var warning = warnings[i] 43 | console.log(' ' + warning) 44 | } 45 | console.log() 46 | process.exit(1) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /build/dev-client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | require('eventsource-polyfill') 3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 4 | 5 | hotClient.subscribe(function (event) { 6 | if (event.action === 'reload') { 7 | window.location.reload() 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /build/dev-server.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | var config = require('../config') 4 | if (!process.env.NODE_ENV) { 5 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) 6 | } 7 | 8 | var opn = require('opn') 9 | var path = require('path') 10 | var express = require('express') 11 | var webpack = require('webpack') 12 | var proxyMiddleware = require('http-proxy-middleware') 13 | var webpackConfig = require('./webpack.dev.conf') 14 | 15 | // default port where dev server listens for incoming traffic 16 | var port = process.env.PORT || config.dev.port 17 | // automatically open browser, if not set will be false 18 | var autoOpenBrowser = !!config.dev.autoOpenBrowser 19 | // Define HTTP proxies to your custom API backend 20 | // https://github.com/chimurai/http-proxy-middleware 21 | var proxyTable = config.dev.proxyTable 22 | 23 | var app = express() 24 | var compiler = webpack(webpackConfig) 25 | 26 | var devMiddleware = require('webpack-dev-middleware')(compiler, { 27 | publicPath: webpackConfig.output.publicPath, 28 | quiet: true 29 | }) 30 | 31 | var hotMiddleware = require('webpack-hot-middleware')(compiler, { 32 | log: () => {} 33 | }) 34 | // force page reload when html-webpack-plugin template changes 35 | compiler.plugin('compilation', function (compilation) { 36 | compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { 37 | hotMiddleware.publish({ action: 'reload' }) 38 | cb() 39 | }) 40 | }) 41 | 42 | // proxy api requests 43 | Object.keys(proxyTable).forEach(function (context) { 44 | var options = proxyTable[context] 45 | if (typeof options === 'string') { 46 | options = { target: options } 47 | } 48 | app.use(proxyMiddleware(options.filter || context, options)) 49 | }) 50 | 51 | // handle fallback for HTML5 history API 52 | app.use(require('connect-history-api-fallback')()) 53 | 54 | // serve webpack bundle output 55 | app.use(devMiddleware) 56 | 57 | // enable hot-reload and state-preserving 58 | // compilation error display 59 | app.use(hotMiddleware) 60 | 61 | // serve pure static assets 62 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) 63 | app.use(staticPath, express.static('./static')) 64 | 65 | var uri = 'http://localhost:' + port 66 | 67 | var _resolve 68 | var readyPromise = new Promise(resolve => { 69 | _resolve = resolve 70 | }) 71 | 72 | console.log('> Starting dev server...') 73 | devMiddleware.waitUntilValid(() => { 74 | console.log('> Listening at ' + uri + '\n') 75 | // when env is testing, don't need open it 76 | if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { 77 | opn(uri) 78 | } 79 | _resolve() 80 | }) 81 | 82 | var server = app.listen(port) 83 | 84 | module.exports = { 85 | ready: readyPromise, 86 | close: () => { 87 | server.close() 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /build/utils.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 4 | 5 | exports.assetsPath = function (_path) { 6 | var assetsSubDirectory = process.env.NODE_ENV === 'production' 7 | ? config.build.assetsSubDirectory 8 | : config.dev.assetsSubDirectory 9 | return path.posix.join(assetsSubDirectory, _path) 10 | } 11 | 12 | exports.cssLoaders = function (options) { 13 | options = options || {} 14 | 15 | var cssLoader = { 16 | loader: 'css-loader', 17 | options: { 18 | minimize: process.env.NODE_ENV === 'production', 19 | sourceMap: options.sourceMap 20 | } 21 | } 22 | 23 | // generate loader string to be used with extract text plugin 24 | function generateLoaders (loader, loaderOptions) { 25 | var loaders = [cssLoader] 26 | if (loader) { 27 | loaders.push({ 28 | loader: loader + '-loader', 29 | options: Object.assign({}, loaderOptions, { 30 | sourceMap: options.sourceMap 31 | }) 32 | }) 33 | } 34 | 35 | // Extract CSS when that option is specified 36 | // (which is the case during production build) 37 | if (options.extract) { 38 | return ExtractTextPlugin.extract({ 39 | use: loaders, 40 | fallback: 'vue-style-loader' 41 | }) 42 | } else { 43 | return ['vue-style-loader'].concat(loaders) 44 | } 45 | } 46 | 47 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 48 | return { 49 | css: generateLoaders(), 50 | postcss: generateLoaders(), 51 | less: generateLoaders('less'), 52 | sass: generateLoaders('sass', { indentedSyntax: true }), 53 | scss: generateLoaders('sass'), 54 | stylus: generateLoaders('stylus'), 55 | styl: generateLoaders('stylus') 56 | } 57 | } 58 | 59 | // Generate loaders for standalone style files (outside of .vue) 60 | exports.styleLoaders = function (options) { 61 | var output = [] 62 | var loaders = exports.cssLoaders(options) 63 | for (var extension in loaders) { 64 | var loader = loaders[extension] 65 | output.push({ 66 | test: new RegExp('\\.' + extension + '$'), 67 | use: loader 68 | }) 69 | } 70 | return output 71 | } 72 | -------------------------------------------------------------------------------- /build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var config = require('../config') 3 | var isProduction = process.env.NODE_ENV === 'production' 4 | 5 | module.exports = { 6 | loaders: utils.cssLoaders({ 7 | sourceMap: isProduction 8 | ? config.build.productionSourceMap 9 | : config.dev.cssSourceMap, 10 | extract: isProduction 11 | }) 12 | } 13 | -------------------------------------------------------------------------------- /build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var config = require('../config') 4 | var vueLoaderConfig = require('./vue-loader.conf') 5 | 6 | function resolve(dir) { 7 | return path.join(__dirname, '..', dir) 8 | } 9 | 10 | module.exports = { 11 | entry: { 12 | app: './src/main.js' 13 | }, 14 | output: { 15 | path: config.build.assetsRoot, 16 | filename: '[name].js', 17 | publicPath: process.env.NODE_ENV === 'production' 18 | ? config.build.assetsPublicPath 19 | : config.dev.assetsPublicPath 20 | }, 21 | resolve: { 22 | extensions: ['.js', '.vue', '.json'], 23 | alias: { 24 | 'vue$': 'vue/dist/vue.esm.js', 25 | '@': resolve('src') 26 | } 27 | }, 28 | module: { 29 | rules: [ 30 | { 31 | test: /\.vue$/, 32 | loader: 'vue-loader', 33 | options: vueLoaderConfig 34 | }, 35 | { 36 | test: /\.js$/, 37 | loader: 'babel-loader', 38 | // include: [resolve('src'), resolve('test')] 39 | include: [ 40 | resolve('src'), 41 | resolve('test'), 42 | resolve('node_modules/vue-echarts'), 43 | resolve('node_modules/resize-detector') 44 | ] 45 | }, 46 | { 47 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 48 | loader: 'url-loader', 49 | options: { 50 | limit: 10000, 51 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 52 | } 53 | }, 54 | { 55 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 56 | loader: 'url-loader', 57 | options: { 58 | limit: 10000, 59 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 60 | } 61 | } 62 | ] 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var webpack = require('webpack') 3 | var config = require('../config') 4 | var merge = require('webpack-merge') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | var HtmlWebpackPlugin = require('html-webpack-plugin') 7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 8 | 9 | // add hot-reload related code to entry chunks 10 | Object.keys(baseWebpackConfig.entry).forEach(function (name) { 11 | baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) 12 | }) 13 | 14 | module.exports = merge(baseWebpackConfig, { 15 | module: { 16 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) 17 | }, 18 | // cheap-module-eval-source-map is faster for development 19 | devtool: '#cheap-module-eval-source-map', 20 | plugins: [ 21 | new webpack.DefinePlugin({ 22 | 'process.env': config.dev.env 23 | }), 24 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage 25 | new webpack.HotModuleReplacementPlugin(), 26 | new webpack.NoEmitOnErrorsPlugin(), 27 | // https://github.com/ampedandwired/html-webpack-plugin 28 | new HtmlWebpackPlugin({ 29 | filename: 'index.html', 30 | template: 'index.html', 31 | inject: true 32 | }), 33 | new FriendlyErrorsPlugin() 34 | ] 35 | }) 36 | -------------------------------------------------------------------------------- /build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var webpack = require('webpack') 4 | var config = require('../config') 5 | var merge = require('webpack-merge') 6 | var baseWebpackConfig = require('./webpack.base.conf') 7 | var CopyWebpackPlugin = require('copy-webpack-plugin') 8 | var HtmlWebpackPlugin = require('html-webpack-plugin') 9 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 10 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 11 | 12 | var env = config.build.env 13 | 14 | var webpackConfig = merge(baseWebpackConfig, { 15 | module: { 16 | rules: utils.styleLoaders({ 17 | sourceMap: config.build.productionSourceMap, 18 | extract: true 19 | }) 20 | }, 21 | devtool: config.build.productionSourceMap ? '#source-map' : false, 22 | output: { 23 | path: config.build.assetsRoot, 24 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 25 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 26 | }, 27 | plugins: [ 28 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 29 | new webpack.DefinePlugin({ 30 | 'process.env': env 31 | }), 32 | new webpack.optimize.UglifyJsPlugin({ 33 | compress: { 34 | warnings: false 35 | }, 36 | sourceMap: true 37 | }), 38 | // extract css into its own file 39 | new ExtractTextPlugin({ 40 | filename: utils.assetsPath('css/[name].[contenthash].css') 41 | }), 42 | // Compress extracted CSS. We are using this plugin so that possible 43 | // duplicated CSS from different components can be deduped. 44 | new OptimizeCSSPlugin({ 45 | cssProcessorOptions: { 46 | safe: true 47 | } 48 | }), 49 | // generate dist index.html with correct asset hash for caching. 50 | // you can customize output by editing /index.html 51 | // see https://github.com/ampedandwired/html-webpack-plugin 52 | new HtmlWebpackPlugin({ 53 | filename: config.build.index, 54 | template: 'index.html', 55 | inject: true, 56 | minify: { 57 | removeComments: true, 58 | collapseWhitespace: true, 59 | removeAttributeQuotes: true 60 | // more options: 61 | // https://github.com/kangax/html-minifier#options-quick-reference 62 | }, 63 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 64 | chunksSortMode: 'dependency' 65 | }), 66 | // split vendor js into its own file 67 | new webpack.optimize.CommonsChunkPlugin({ 68 | name: 'vendor', 69 | minChunks: function (module, count) { 70 | // any required modules inside node_modules are extracted to vendor 71 | return ( 72 | module.resource && 73 | /\.js$/.test(module.resource) && 74 | module.resource.indexOf( 75 | path.join(__dirname, '../node_modules') 76 | ) === 0 77 | ) 78 | } 79 | }), 80 | // extract webpack runtime and module manifest to its own file in order to 81 | // prevent vendor hash from being updated whenever app bundle is updated 82 | new webpack.optimize.CommonsChunkPlugin({ 83 | name: 'manifest', 84 | chunks: ['vendor'] 85 | }), 86 | // copy custom static assets 87 | new CopyWebpackPlugin([ 88 | { 89 | from: path.resolve(__dirname, '../static'), 90 | to: config.build.assetsSubDirectory, 91 | ignore: ['.*'] 92 | } 93 | ]) 94 | ] 95 | }) 96 | 97 | if (config.build.productionGzip) { 98 | var CompressionWebpackPlugin = require('compression-webpack-plugin') 99 | 100 | webpackConfig.plugins.push( 101 | new CompressionWebpackPlugin({ 102 | asset: '[path].gz[query]', 103 | algorithm: 'gzip', 104 | test: new RegExp( 105 | '\\.(' + 106 | config.build.productionGzipExtensions.join('|') + 107 | ')$' 108 | ), 109 | threshold: 10240, 110 | minRatio: 0.8 111 | }) 112 | ) 113 | } 114 | 115 | if (config.build.bundleAnalyzerReport) { 116 | var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 117 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 118 | } 119 | 120 | module.exports = webpackConfig 121 | -------------------------------------------------------------------------------- /config/dev.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var prodEnv = require('./prod.env') 3 | 4 | module.exports = merge(prodEnv, { 5 | NODE_ENV: '"development"' 6 | }) 7 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | // see http://vuejs-templates.github.io/webpack for documentation. 2 | var path = require('path') 3 | 4 | module.exports = { 5 | build: { 6 | env: require('./prod.env'), 7 | index: path.resolve(__dirname, '../dist/index.html'), 8 | assetsRoot: path.resolve(__dirname, '../dist'), 9 | assetsSubDirectory: 'static', 10 | assetsPublicPath: '/', 11 | productionSourceMap: true, 12 | // Gzip off by default as many popular static hosts such as 13 | // Surge or Netlify already gzip all static assets for you. 14 | // Before setting to `true`, make sure to: 15 | // npm install --save-dev compression-webpack-plugin 16 | productionGzip: false, 17 | productionGzipExtensions: ['js', 'css'], 18 | // Run the build command with an extra argument to 19 | // View the bundle analyzer report after build finishes: 20 | // `npm run build --report` 21 | // Set to `true` or `false` to always turn it on or off 22 | bundleAnalyzerReport: process.env.npm_config_report 23 | }, 24 | dev: { 25 | env: require('./dev.env'), 26 | port: 1234, 27 | autoOpenBrowser: true, 28 | assetsSubDirectory: 'static', 29 | assetsPublicPath: '/', 30 | proxyTable: { 31 | '/weipxiu': { 32 | target: 'http://api.douban.com/v2', 33 | changeOrigin: true, 34 | pathRewrite: { 35 | '^/weipxiu': '' 36 | } 37 | } 38 | }, 39 | // CSS Sourcemaps off by default because relative paths are "buggy" 40 | // with this option, according to the CSS-Loader README 41 | // (https://github.com/webpack/css-loader#sourcemaps) 42 | // In our experience, they generally work as expected, 43 | // just be aware of this issue when enabling this option. 44 | cssSourceMap: false 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /config/prod.env.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NODE_ENV: '"production"' 3 | } 4 | -------------------------------------------------------------------------------- /debug.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weipxiu/Vue-vuex/c459f1073416c34936ac6a6c909003d14c3c5867/debug.log -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | vuex-examplate 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vuex-examplate", 3 | "version": "1.0.0", 4 | "description": "A Vue.js project", 5 | "author": "WYseven ", 6 | "private": true, 7 | "scripts": { 8 | "dev": "node build/dev-server.js", 9 | "start": "node build/dev-server.js", 10 | "build": "node build/build.js" 11 | }, 12 | "dependencies": { 13 | "axios": "^0.16.2", 14 | "echarts": "^4.7.0", 15 | "qiankun": "^2.7.5", 16 | "vue": "^2.3.3", 17 | "vue-axios": "^2.0.2", 18 | "vue-echarts": "^5.0.0-beta.0", 19 | "vue-router": "^2.3.1", 20 | "vuex": "^2.3.1" 21 | }, 22 | "devDependencies": { 23 | "autoprefixer": "^6.7.2", 24 | "babel-core": "^6.22.1", 25 | "babel-loader": "^6.2.10", 26 | "babel-plugin-transform-runtime": "^6.22.0", 27 | "babel-preset-env": "^1.3.2", 28 | "babel-preset-stage-2": "^6.22.0", 29 | "babel-register": "^6.22.0", 30 | "chalk": "^1.1.3", 31 | "connect-history-api-fallback": "^1.3.0", 32 | "copy-webpack-plugin": "^4.0.1", 33 | "css-loader": "^0.28.0", 34 | "eventsource-polyfill": "^0.9.6", 35 | "express": "^4.14.1", 36 | "extract-text-webpack-plugin": "^2.0.0", 37 | "file-loader": "^0.11.1", 38 | "friendly-errors-webpack-plugin": "^1.1.3", 39 | "html-webpack-plugin": "^2.28.0", 40 | "http-proxy-middleware": "^0.17.3", 41 | "webpack-bundle-analyzer": "^2.2.1", 42 | "semver": "^5.3.0", 43 | "shelljs": "^0.7.6", 44 | "opn": "^4.0.2", 45 | "optimize-css-assets-webpack-plugin": "^1.3.0", 46 | "ora": "^1.2.0", 47 | "rimraf": "^2.6.0", 48 | "url-loader": "^0.5.8", 49 | "vue-loader": "^12.1.0", 50 | "vue-style-loader": "^3.0.1", 51 | "vue-template-compiler": "^2.3.3", 52 | "webpack": "^2.6.1", 53 | "webpack-dev-middleware": "^1.10.0", 54 | "webpack-hot-middleware": "^2.18.0", 55 | "webpack-merge": "^4.1.0", 56 | "babel-eslint": "8.2.6", 57 | "eslint": "4.19.1", 58 | "eslint-friendly-formatter": "4.0.1", 59 | "eslint-loader": "2.0.0", 60 | "eslint-plugin-vue": "4.7.1" 61 | }, 62 | "engines": { 63 | "node": ">= 4.0.0", 64 | "npm": ">= 3.0.0" 65 | }, 66 | "browserslist": [ 67 | "> 1%", 68 | "last 2 versions", 69 | "not ie <= 8" 70 | ] 71 | } 72 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 42 | 43 | 53 | -------------------------------------------------------------------------------- /src/assets/css/select.css: -------------------------------------------------------------------------------- 1 | body{ 2 | margin:0; 3 | font-family:"微软雅黑"; 4 | } 5 | ul,li{ 6 | margin:0; 7 | padding:0; 8 | list-style:none; 9 | } 10 | input{ 11 | outline:none; 12 | cursor: pointer; 13 | } 14 | .clearFix:after{ 15 | display: block; 16 | content:''; 17 | clear:both; 18 | } 19 | .warp{ 20 | width: 348px; 21 | padding:100px 76px 50px; 22 | margin:50px auto; 23 | background:url(../images/select_bg.png) no-repeat; 24 | box-shadow:2px 2px 10px #6789ad; 25 | } 26 | .searchIpt{ 27 | position: relative; 28 | width: 336px; 29 | border:1px solid #3736ae; 30 | padding:5px; 31 | border-radius:24px; 32 | background: #e4e4fe; 33 | } 34 | .searchIpt input{ 35 | line-height: 34px; 36 | border-radius:18px; 37 | } 38 | .searchIpt input:nth-of-type(1){ 39 | float: left; 40 | width: 228px; 41 | padding-left: 40px; 42 | border:1px solid #c9c9d5; 43 | background: #d9d9e2; 44 | 45 | } 46 | .searchIpt input:nth-of-type(2){ 47 | float: right; 48 | width: 58px; 49 | height: 36px; 50 | border:1px solid #fd635e; 51 | background: #fd635e; 52 | } 53 | .searchIpt span{ 54 | position: absolute; 55 | top:12px; 56 | left: 15px; 57 | width: 23px; 58 | height: 23px; 59 | background: url(../images/select_search.png) no-repeat; 60 | } 61 | .searchIpt input:nth-of-type(1):focus{ 62 | background: #fff; 63 | border-color:#fd635e; 64 | } 65 | .list{ 66 | margin-top:9px; 67 | } 68 | .list li{ 69 | margin:3px 0; 70 | color:#333; 71 | line-height: 30px; 72 | padding-left: 16px; 73 | width: 270px; 74 | box-sizing:border-box; 75 | border-radius:14px; 76 | 77 | } 78 | .list li.active,.list li:hover{ 79 | color:#fff; 80 | background: #fd635e; 81 | cursor: pointer; 82 | } 83 | -------------------------------------------------------------------------------- /src/assets/images/select_bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weipxiu/Vue-vuex/c459f1073416c34936ac6a6c909003d14c3c5867/src/assets/images/select_bg.png -------------------------------------------------------------------------------- /src/assets/images/select_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weipxiu/Vue-vuex/c459f1073416c34936ac6a6c909003d14c3c5867/src/assets/images/select_search.png -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weipxiu/Vue-vuex/c459f1073416c34936ac6a6c909003d14c3c5867/src/assets/logo.png -------------------------------------------------------------------------------- /src/components/about.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 20 | -------------------------------------------------------------------------------- /src/components/charts.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 120 | 127 | -------------------------------------------------------------------------------- /src/components/home.vue: -------------------------------------------------------------------------------- 1 | 62 | 63 | 114 | 131 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | // The Vue build version to load with the `import` command 2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias. 3 | import Vue from 'vue' 4 | import App from './App' 5 | import router from './router' 6 | import store from './store' 7 | import actions from './shared/actions.js' 8 | 9 | //全局引入ECharts 10 | // import ECharts from 'vue-echarts' 11 | // 饼状图 12 | // import 'echarts/lib/chart/pie' 13 | // Vue.component('v-chart', ECharts) 14 | 15 | Vue.config.productionTip = false 16 | 17 | import '@/assets/css/select.css' 18 | 19 | // 新增内容开始 20 | import { registerMicroApps, start } from 'qiankun' //新增部分,导入qiankun中的两个方法 21 | const apps = [ 22 | { 23 | name: 'vite2_vue3', //子应用的名称 24 | entry: '//localhost:3000',//子应用的域名 25 | container: '#vueContainer',//承载子应用的容器,在上面App.vue中定义 26 | activeRule: '/vueChild', // 被激活的子应用的路由 27 | props: { 28 | actions, 29 | msg: '主应用传递变量msg', 30 | data1: '数据1', 31 | } 32 | } 33 | ] 34 | registerMicroApps(apps);//注册子应用 35 | // 启动qiankun 36 | start({ 37 | sandbox:true // 默认(true)情况下沙箱可以确保单实例场景子应用之间的样式隔离,但是无法确保主应用跟子应用、或者多实例场景的子应用样式隔离。当配置为 { strictStyleIsolation: true } 时表示开启严格的样式隔离模式。这种模式下 qiankun 会为每个微应用的容器包裹上一个 shadow dom 节点,从而确保微应用的样式不会对全局造成影响。 38 | }); 39 | // 新增内容结束 40 | 41 | /* eslint-disable no-new */ 42 | new Vue({ 43 | el: '#app_main', 44 | router, 45 | store, 46 | template: '', 47 | components: { App } 48 | }) 49 | -------------------------------------------------------------------------------- /src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Router from 'vue-router' 3 | 4 | 5 | import about from '@/components/about' 6 | import home from '@/components/home' 7 | // import charts from '@/components/charts' 8 | 9 | Vue.use(Router) 10 | 11 | export default new Router({ 12 | mode: 'history', 13 | base: '', 14 | routes: [ 15 | { 16 | path: '/', 17 | name: 'home', 18 | component: home 19 | }, 20 | { 21 | path: '/about', 22 | name: 'about', 23 | component: about 24 | }, 25 | // { 26 | // path: '/charts', 27 | // name: 'charts', 28 | // component: charts 29 | // } 30 | ] 31 | }) 32 | -------------------------------------------------------------------------------- /src/shared/actions.js: -------------------------------------------------------------------------------- 1 | import { initGlobalState, MicroAppStateActions } from 'qiankun' 2 | // import _store from '@/store' 3 | // 父应用中使用initGlobalState设置全局状态actions并导出供其他组件使用 4 | const initialState = { 5 | //这可以写初始化数据 6 | testData: '测试' 7 | } 8 | // 初始化 9 | const actions = initGlobalState(initialState) 10 | 11 | actions.onGlobalStateChange((state, prevState) => { 12 | console.log("主应用state变更前:", prevState); 13 | console.log("主应用state变更后:", state); 14 | // _store.commit("setData", state) // 在store存储相关数据 15 | }) 16 | export default actions 17 | -------------------------------------------------------------------------------- /src/store/actions.js: -------------------------------------------------------------------------------- 1 | export default { 2 | changeNumber({ commit, state, rootState, dispatch, getters }, payload) { 3 | setTimeout(() => { 4 | // 改变状态,提交mutations 5 | // commit("addIncrement", payload) //第一种更新addIncrement 6 | commit('save', { count: state.count + payload.n }) 7 | dispatch("textAction", { test: '异步回调拿到的参数' }) 8 | }, 1000) 9 | }, 10 | textAction($store, options) {//接收上面dispatch提交过来的参数 11 | //console.log($store, options)//相当于一个异步操作里的回调函数 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/store/commoms/about.js: -------------------------------------------------------------------------------- 1 | export default { 2 | namespaced: true, 3 | state: { 4 | msg: '这是关于我页面!' 5 | }, 6 | mutations: { 7 | save: (state, payload) => { 8 | console.log('payload', payload) 9 | Object.keys(payload).forEach(e => { 10 | if (state.hasOwnProperty(e)) { 11 | state[e] = payload[e] 12 | } else { 13 | console.error('Sorry,更新失败:属性' + e + '在对应的modules模块中未定义!') 14 | } 15 | }) 16 | } 17 | }, 18 | actions: { 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /src/store/commoms/index.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | export default { 3 | namespaced: true, //定义module另外命名时,需要在module中加一个命名空间namespaced: true属性,否则命名无法暴露出来,导致报[vuex] module namespace not found in mapState()等错误。 4 | state: { 5 | title: '支付宝到账100万!', 6 | listData: null 7 | }, 8 | mutations: { 9 | save: (state, payload) => { 10 | console.log('payload', payload) 11 | Object.keys(payload).forEach(e => { 12 | if (state.hasOwnProperty(e)) { 13 | state[e] = payload[e] 14 | } else { 15 | console.error('Sorry,更新失败:属性' + e + '在对应的modules模块中未定义!') 16 | } 17 | }) 18 | }, 19 | changeTitle(state, payload) { 20 | state.title = payload.title 21 | }, 22 | changeList(state, list) { 23 | state.listData = list; 24 | } 25 | }, 26 | actions: { 27 | getListAction({ commit, state, rootState, dispatch, getters }, payload) { 28 | // 发送请求 29 | axios.get('weipxiu/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a&start=0&count=10') 30 | .then((data) => { 31 | // console.log('state',state, rootState) 32 | 33 | commit('localtAboutfrom/save', { msg: 'about模块数据被改变了' }, { root: true }) 34 | // 模块之间数据交互,模块化后当前commit被局域化,通过{ root: true }后将代理到全局,这样后将在全局环境下找到'localtAboutfrom/save'模块从而改变对应数据 35 | 36 | commit('save', { title: '顶层数据被改变!' }, { root: true }) 37 | //通过{ root: true }修改底层数据,请不要直接通过rootState进行赋值,一切数据都通过commit 38 | 39 | commit("changeList", data.data); // 拿到数据后,提交mutations,改变状态 40 | }) 41 | .catch((error) => { 42 | console.log(error) 43 | }) 44 | } 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /src/store/getters.js: -------------------------------------------------------------------------------- 1 | export default {//类似计算属性 2 | filterCount(state) { 3 | return state.count >= 120 ? 120 : state.count; 4 | }, 5 | computedSum(state) { 6 | return state.sum >= 200 ? 200 : state.sum 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuex from 'vuex' 3 | import axios from 'axios' 4 | import mutations from './mutations' 5 | import getters from './getters' 6 | import actions from './actions' 7 | import localtModule from './commoms' 8 | import localtAboutfrom from './commoms/about' 9 | 10 | Vue.use(Vuex) 11 | 12 | export default new Vuex.Store({ 13 | strict: true, //在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到。 14 | state: { 15 | count: 100, 16 | sum: 90, 17 | title: '我是一条顶层数据', 18 | money: 100 19 | }, 20 | mutations, 21 | getters, 22 | actions, 23 | modules: { // vuex模块化 24 | localtModule, 25 | localtAboutfrom 26 | } 27 | }) 28 | 29 | -------------------------------------------------------------------------------- /src/store/mutations.js: -------------------------------------------------------------------------------- 1 | export default {//payload接受页面事件交互传过来的参数值 2 | save: (state, payload) => { 3 | console.log('payload', payload) 4 | Object.keys(payload).forEach(e => { 5 | if (state.hasOwnProperty(e)) { 6 | state[e] = payload[e] 7 | } else { 8 | console.error('Sorry,更新失败:属性' + e + '在对应的modules模块中未定义!') 9 | } 10 | }) 11 | }, 12 | addIncrement(state, payload) { 13 | state.count += payload.n; 14 | }, 15 | sumReduce(state, payload) { 16 | state.count -= payload.de; 17 | }, 18 | sumFn(state, payload) { 19 | state.sum += payload.add; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weipxiu/Vue-vuex/c459f1073416c34936ac6a6c909003d14c3c5867/static/.gitkeep --------------------------------------------------------------------------------