vux 进阶系列之vuex


vuex 进阶系列之vuex

  • 还是用todoList 来熟悉演示vuex的基本用法
  • 注释部分为新知识点,todoList 相关代码会有所改变

开始吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> vue 进阶系列之全局 API 的使用</title>
<style>
.todo-list {
margin: 100px auto;
width: 600px;
text-align: center;
font-family: '微软雅黑';
}

.display-item li{
text-align: left;
padding-left: 1rem;
color: #bbbbbb;
line-height: 2rem;
}

.input-todo-item>input {
width: 300px;
height: 35px;
border: 1px solid #bbb;
border-radius: 4px;
padding: 0 1rem;
}

.input-todo-item>input:focus {
border-radius: 4px;
}

.input-todo-item>button {
line-height: 35px;
color: #ffffff;
background-color: red;
outline: none;
opacity: .6;
border-radius: 4px;
border: none;
padding: 0 1rem;
cursor: pointer;
}


.input-todo-item>button:hover, .router-link:hover {
opacity: 1;
}

.router-link {
display: inline-block;
color: #ffffff;
background-color: green;
opacity: .6;
border-radius: 4px;
padding: .5rem 1rem;
cursor: pointer;
text-decoration: none;
}


.disableBtn {
background-color: #bbb !important;
opacity: 1 !important;
}

.samll-widget {
display: inline-block;
height: 20px;
padding: 2px .5rem;
line-height: 20px;
text-align: center;
color: #ffffff;
transition: all 1s;
border-radius: 2px;
margin-left: 1rem;
opacity: .5;
cursor: pointer;
}

.samll-widget:hover {
opacity: 1;
}

.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}

.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}

</style>
</head>

<body>
<div id="mount-point">
<div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex@2.0.0"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
<script>
const inputTpl =
`<div class="input-todo-item">
<input v-focus type="text" v-model="inputValue"/>
<button
ref="addbtn"
@click="addClick"
:disabled="disableAddBtn"
:class="{disableBtn: disableAddBtn}">
{{ add | capitalize}}
</button>
</div>
`
const disTpl =
`<div class="display-item">
<ul>
<li
v-for="(item, index) in disList"
:key="index"
:style="{textDecorationLine: item.isCompleted ? 'line-through' : 'none'}">
{{item.text}}
<small-widget type="delete" index="index" @onClickWidget="deleteItem(index)">
<template v-slot:widget>delete</template>
</small-widget>
<small-widget type="finished" index="index">
<template v-slot:widget>
<router-link style="color: #fff" :to="{name: 'edit', params: {}}">edit</router-link>
</template>
</small-widget>
<small-widget type="link" index="index">
<template v-slot:widget>
<router-link style="color: #fff" :to="{path: '/detail/' + item.id, params: {}}">view</router-link>
</template>
</small-widget>
</li>
</ul>
</div>`
const tpl =
`<div class="todo-list">
<input-item @onAddItem="addItemToList"/>
<display-item :disList="todoLists"/>
</div>`
const widget = Vue.compile(`<span ref="small-widget" class="samll-widget" @click="handleClick"><slot name="widget"></slot></span>`)
Vue.component('small-widget', {
props: {
type: {
type: String
},
index: {
type: String
}
},
computed: {
color () {
if (this.type === 'delete') {
return 'red'
} else if (this.type === 'remind') {
return 'yellow'
} else if (this.type === 'link') {
return 'blue'
} else {
return 'green'
}
}
},
mounted () {
this.$refs['small-widget'].style.backgroundColor = this.color
},
methods: {
handleClick () {
this.$emit('onClickWidget')
}
},
render: widget.render
})
const DisplayItem = Vue.extend({
template: disTpl,
props: {
disList: {
type: Array
}
},
methods: {
deleteItem(index) {
this.$emit('onDeleteItem', index)
}
}
})
Vue.component('display-item', DisplayItem)
Vue.component('display-item-detail', {
template: `<div>
<div>{{params}}</div>
<router-view></router-view>
</div>`,
computed: {
params () {
return this.$route.params
}
},
mounted () {
console.log('params', this.params)
},
watch: {
'$route' (to, from) {
// ...
}
},
// 组件内的守卫
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
this.name = to.params.name
next()
},
beforeRouteEnter (to, from, next) {
// 在导航完成前获取数据
// getPost(to.params.id, (err, post) => {
// next(vm => vm.setData(err, post))
// })
},
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really leave?')
if (answer) {
next()
} else {
false
}
}
})
// 使用模板选项创建组件
Vue.component('input-item', {
template: inputTpl,
data() {
return {
inputValue: '',
add: 'add'
}
},
computed: {
disableAddBtn() {
return !this.inputValue
}
},
methods: {
addClick() {
console.log(this.disableAddBtn)
if (this.disableAddBtn) return
this.$emit('onAddItem', this.inputValue) // 实例方法/事件
},
toViewDetails () {

}
}
})
// 使用render函数创建组件
const ADD_ITEM_TO_LISTS = 'ADD_ITEM_TO_LISTS'
const DELETE_ITEM_FROM_LISTS = 'DELETE_ITEM_FROM_LISTS'
Vue.component('todo-list', {
computed: {
todoLists () {
return this.$store.state.todo.todoLists
},
completedItemCount () {
return this.$store.state.getters.completedItemCount
},
// ...mapState('todo', {
// count: state =>state.count
// })
// ...mapGetters('todo', [
// 'completedItemCount',
// // ...
// ])
},
methods: {
// ...mapActions('todo',[
// 'increment', // 将 `this.increment()` 映射为`this.$store.dispatch('increment')`

// // `mapActions` 也支持载荷:
// 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
// ]),
addItemToList (value) {
let temO = {
isCompleted: false,
text: value
}
// this.todoLists.push(temO)
// 触发 mutaions 更新 state
this.$store.commit(ADD_ITEM_TO_LISTS, temO)
// 以对象形式分发
this.$store.dispatch({
type: 'ADD_ITEM_TO_LISTS_ASYNC',
value: temO
})
},
deleteItemFromList (index) {
this.$store.commit({
type: DELETE_ITEM_FROM_LISTS,
value: index
})
},
},
render: function (createElement) {
return createElement('div', {'class': {'todo-list': true}}, [
createElement('input-item', {
on: {
onAddItem: this.addItemToList
},
}, this.$slots.default),
createElement('display-item', {
props: {
disList: this.todoLists
},
on: {
onDeleteItem: this.deleteItemFromList
},
}, this.$slots.default),
])
}
})
const routes = [
{path: '/', component: Vue.component('todo-list')},
{
path: '/detail/:id',
name: 'detail',
component: {template: '<display-item-detail/>'},
children: [
{
path:'',
component: {template: `<div>
<h2>{{title}}</h2>
<ol>
<li v-for="(item, index) in flows">{{item}}</li>
</ol>
</div>`,
data () {
return {
title: '',
flows: [
'导航被触发',
'在失活的组件里调用离开守卫',
'调用全局的beforeEach守卫',
'在重复的组件中调用beforRouteUpdate守卫',
'在路由配置里调用beforeEnter',
'解析异步路由组件',
'在被激活的组件里调用beforeRouteEnter',
'调用全局的beforeResolve守卫',
'导航被确认',
'调用全局的afterEach钩子',
'触发dom更新',
'用创建好的实例调用beforeRouteEnter守卫中传给next的回调函数'
]
}
}}
}
]
},
{
path: '/edit',
name: 'edit',
component: {template: `<div>
<router-view name="header"></router-view>
<router-view name="main"></router-view>
<router-view name="footer"></router-view>
</div>`},
children: [
{
path: '',
components: {
header: {template: '<div>header</div>'},
main: {template: '<div>main</div>'},
footer: {template: '<div>footer</div>'}
}
}
],
// 路由独享守卫
beforeEnter: (to, from, next) => {

}
},
{path: '*', component: {template: '<div>你的页面丢失了</div>'}},
]
const router = new VueRouter({
routes,
scrollBehavior (to, from, savedPosition) {
return {
x: 0,
y: 0
}
}
})
router.beforeEach((to, from, next) => {
next()
})
// use vuex
const todo = {
namespaced: true,
state: {
todoLists: [
{
text: '这个周末去song'
}
]
},
getters: {
completedItemCount () {
return state.todoLists.filter(item => item.isCompleted).length
}
},
// 通过 `mutations` 来更新 `state`
mutations: {
[ADD_ITEM_TO_LISTS] (state, payload) {
state.todoLists.push(payload)
},
[DELETE_ITEM_FROM_LISTS] (state, index) {
state.todoLists.splice(payload.value, 1)
}
},
actions: {
[ADD_ITEM_TO_LISTS] (context) {
context.commit(ADD_ITEM_TO_LISTS)
},
[`ADD_ITEM_TO_LISTS_ASYNC`] ({commit}, data) {
let {value} = data
setTimeout(() => {
commit({
type: ADD_ITEM_TO_LISTS,
...value
})
}, 2000)
},
}
}
const store = new Vuex.Store({
// 具有命名空间
modules: {
todo
},
// 全局共享
state: {},
getters: {},
mutations: {},
actions: {}
})
const TodoList = new Vue({
router,
store,
render: function (createElement) {
return createElement('transition', {props: {name: 'fade', mode: 'out-in'}}, [
createElement('router-view')
])
}
})
Vue.directive('focus', {
inserted (el, binding, vNode) {
el.focus()
}
})
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
TodoList.$mount('#mount-point')
</script>
</body>

</html>