Skip to content

Commit 27350ab

Browse files
committed
initialized lesson04 vuex
1 parent edb55eb commit 27350ab

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1337
-0
lines changed

README.md

+82
Original file line numberDiff line numberDiff line change
@@ -962,3 +962,85 @@ methods: {
962962
Clear completed
963963
</button>
964964
````
965+
## lesson04.vue-vuex
966+
967+
> Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
968+
969+
这一节教程中,我们基于`03.vue-todos`将把`vue`的状态管理插件`vuex`整合进来,复制项目`03.vue-todos`改名为`04.vue-vuex-todos`
970+
971+
加入vuex插件库
972+
````
973+
cnpm i vuex --save
974+
````
975+
976+
为了不影响`lesson03`的`store`实现,我们在`src`中新建了一个`vuex-store`文件夹,作为vuex的store存储库
977+
`src/vuex-store/index.js`
978+
````javascript
979+
import Vue from 'vue'
980+
import Vuex from 'vuex'
981+
import uuid from 'uuid'
982+
983+
Vue.use(Vuex)
984+
985+
export default new Vuex.Store({
986+
state: {
987+
todos: [] // 存储所有todos
988+
},
989+
mutations: {
990+
ADD_TODO (state, todoContent) {
991+
state.todos.push({
992+
id: uuid(),
993+
title: todoContent,
994+
completed: false
995+
})
996+
},
997+
REMOVE_TODO (state, todo) {
998+
var todos = state.todos
999+
todos.splice(todos.indexOf(todo), 1)
1000+
},
1001+
COMPLETE_TODO (state, todo) {
1002+
todo.completed = !todo.completed
1003+
}
1004+
},
1005+
actions: {
1006+
addTodo ({ commit }, todoContent) {
1007+
commit('ADD_TODO', todoContent)
1008+
},
1009+
removeTodo ({ commit }, todo) {
1010+
commit('REMOVE_TODO', todo)
1011+
},
1012+
completeTodo ({ commit }, todo) {
1013+
commit('COMPLETE_TODO', todo)
1014+
}
1015+
1016+
},
1017+
getters: {
1018+
todos: state => state.todos.filter((todo) => { return !todo.completed }),
1019+
completedTodos: state => state.todos.filter((todo) => { return todo.completed })
1020+
}
1021+
1022+
})
1023+
````
1024+
1025+
> Vuex 通过 store 选项,提供了一种机制将状态从根组件『注入』到每一个子组件中(需调用 Vue.use(Vuex))
1026+
1027+
src/main.js
1028+
````javascript
1029+
// The Vue build version to load with the `import` command
1030+
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
1031+
import Vue from 'vue'
1032+
import App from './App'
1033+
import router from './router'
1034+
import store from './vuex-store/index'
1035+
1036+
Vue.config.productionTip = false
1037+
1038+
/* eslint-disable no-new */
1039+
new Vue({
1040+
el: '#app',
1041+
router,
1042+
store,
1043+
template: '<App/>',
1044+
components: { App }
1045+
})
1046+
````

lesson/04.vue-vuex-todos/.babelrc

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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
+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
build/*.js
2+
config/*.js

lesson/04.vue-vuex-todos/.eslintrc.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// http://eslint.org/docs/user-guide/configuring
2+
3+
module.exports = {
4+
root: true,
5+
parser: 'babel-eslint',
6+
parserOptions: {
7+
sourceType: 'module'
8+
},
9+
env: {
10+
browser: true
11+
},
12+
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-s
13+
// tyle
14+
extends: 'standard',
15+
exclude: [
16+
/node_modules/ // 排除第三方文件
17+
],
18+
// required to lint *.vue files
19+
plugins: ['html'],
20+
// add your custom rules here
21+
'rules': {
22+
// allow paren-less arrow functions
23+
'arrow-parens': 0,
24+
// allow async-await
25+
'generator-star-spacing': 0,
26+
// allow debugger during development
27+
'no-debugger': process.env.NODE_ENV === 'production'
28+
? 2
29+
: 0
30+
}
31+
}

lesson/04.vue-vuex-todos/.gitignore

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.DS_Store
2+
node_modules/
3+
dist/
4+
npm-debug.log
5+
yarn-error.log
6+
test/unit/coverage
7+
test/e2e/reports
8+
selenium-debug.log
+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
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+
}

lesson/04.vue-vuex-todos/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# 04.vue-vuex-todos
2+
3+
> A Vue.js project
4+
5+
## Build Setup
6+
7+
``` bash
8+
# install dependencies
9+
npm install
10+
11+
# serve with hot reload at localhost:8080
12+
npm run dev
13+
14+
# build for production with minification
15+
npm run build
16+
17+
# build for production and view the bundle analyzer report
18+
npm run build --report
19+
20+
# run unit tests
21+
npm run unit
22+
23+
# run e2e tests
24+
npm run e2e
25+
26+
# run all tests
27+
npm test
28+
```
29+
30+
For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
var chalk = require('chalk')
2+
var semver = require('semver')
3+
var packageConfig = require('../package.json')
4+
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+
name: 'npm',
17+
currentVersion: exec('npm --version'),
18+
versionRequirement: packageConfig.engines.npm
19+
}
20+
]
21+
22+
module.exports = function () {
23+
var warnings = []
24+
for (var i = 0; i < versionRequirements.length; i++) {
25+
var mod = versionRequirements[i]
26+
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
27+
warnings.push(mod.name + ': ' +
28+
chalk.red(mod.currentVersion) + ' should be ' +
29+
chalk.green(mod.versionRequirement)
30+
)
31+
}
32+
}
33+
34+
if (warnings.length) {
35+
console.log('')
36+
console.log(chalk.yellow('To use this template, you must update following to modules:'))
37+
console.log()
38+
for (var i = 0; i < warnings.length; i++) {
39+
var warning = warnings[i]
40+
console.log(' ' + warning)
41+
}
42+
console.log()
43+
process.exit(1)
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
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 = process.env.NODE_ENV === 'testing'
14+
? require('./webpack.prod.conf')
15+
: require('./webpack.dev.conf')
16+
17+
// default port where dev server listens for incoming traffic
18+
var port = process.env.PORT || config.dev.port
19+
// automatically open browser, if not set will be false
20+
var autoOpenBrowser = !!config.dev.autoOpenBrowser
21+
// Define HTTP proxies to your custom API backend
22+
// https://github.com/chimurai/http-proxy-middleware
23+
var proxyTable = config.dev.proxyTable
24+
25+
var app = express()
26+
var compiler = webpack(webpackConfig)
27+
28+
var devMiddleware = require('webpack-dev-middleware')(compiler, {
29+
publicPath: webpackConfig.output.publicPath,
30+
quiet: true
31+
})
32+
33+
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
34+
log: () => {}
35+
})
36+
// force page reload when html-webpack-plugin template changes
37+
compiler.plugin('compilation', function (compilation) {
38+
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
39+
hotMiddleware.publish({ action: 'reload' })
40+
cb()
41+
})
42+
})
43+
44+
// proxy api requests
45+
Object.keys(proxyTable).forEach(function (context) {
46+
var options = proxyTable[context]
47+
if (typeof options === 'string') {
48+
options = { target: options }
49+
}
50+
app.use(proxyMiddleware(options.filter || context, options))
51+
})
52+
53+
// handle fallback for HTML5 history API
54+
app.use(require('connect-history-api-fallback')())
55+
56+
// serve webpack bundle output
57+
app.use(devMiddleware)
58+
59+
// enable hot-reload and state-preserving
60+
// compilation error display
61+
app.use(hotMiddleware)
62+
63+
// serve pure static assets
64+
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
65+
app.use(staticPath, express.static('./static'))
66+
67+
var uri = 'http://localhost:' + port
68+
69+
var _resolve
70+
var readyPromise = new Promise(resolve => {
71+
_resolve = resolve
72+
})
73+
74+
console.log('> Starting dev server...')
75+
devMiddleware.waitUntilValid(() => {
76+
console.log('> Listening at ' + uri + '\n')
77+
// when env is testing, don't need open it
78+
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
79+
opn(uri)
80+
}
81+
_resolve()
82+
})
83+
84+
var server = app.listen(port)
85+
86+
module.exports = {
87+
ready: readyPromise,
88+
close: () => {
89+
server.close()
90+
}
91+
}

0 commit comments

Comments
 (0)