F2E 拉賽 Vuex

What is Vuex ?
- 單向資料流
- Flux design pettern
- 統一管理應用程式所有狀態

狀態管理模式-官方 vue 計數器說明
new Vue({
data () {
return {
count: 0
}
},
template: `
<div>{{ count }}</div>
`,
methods: {
increment () {
this.count++
}
}
})
Vuex flow

Vuex Install
Vuex git
Vuex gitbook
建立資料結構
├─src
│ ├─components
│ ├─router
│ ├─store (new)
│ │ └─index.js (必備預設檔名)
│ └─main.js
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {}
const getters = {}
const actions = {}
const mutations = {}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
main.js
...
import store from './store';
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
角色分析
腳色 |
職權 |
state |
存放 APP 所有 state |
action |
調用 mutation 函式及處理 ajax (非同步) |
getter |
負責取 state 資料 |
mutation |
負責改變 state 資料 (同步) |
在 Vue 使用 Vuex Action
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'increment'
]),
...mapActions({
add: 'increment'
}),
actionIncrement(){
this.$store.dispatch('increment')
}
}
}
在 Vue 使用 Vuex Getter
import { mapGetters } from 'vuex'
export default {
data () {
return {
count: this.$store.state.count
}
},
computed: {
...mapGetters([
'getCount'
]),
...mapGetters({
count: 'getCount'
})
}
}
Vue 套用了 Vuex


學會 Vuex 了吧!?
Reference