1)多個視圖依賴於同一狀態vue
2)來自不一樣視圖的行爲須要變動同一狀態vuex
Vuex則是把組件的共享狀態抽取出來,以一個全局單例模式管理npm
同時,經過定義和隔離狀態管理中的各類概念並強制遵照必定的規則,代碼變得更結構化、易維護數組
以上就是vuex的思想緩存
store
中存儲的各個狀態。store
中狀態的執行者, 只能是同步操做 。import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 能夠包含異步操做
// context 是一個與 store 實例具備相同方法和屬性的 context 對象
}
}
})
// 注入到根實例
new Vue({
el: '#app',
// 把 store 對象提供給 「store」 選項,這能夠把 store 的實例注入全部的子組件
store,
template: '<App/>',
components: { App }
})
template: `<div>{{ count }}</div>`,app
computed: { count () { return this.$store.state.count // count 爲某個狀態 } }異步
}
模塊化
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
經過屬性訪問
咱們能夠很容易在任何組件中使用他
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
也能夠經過讓 getter 返回一個函數,來實現給 getter 傳參。在對 store 裏的數組進行查詢時很是有用。函數
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } }
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意:getter 在經過方法訪問時,每次都會去進行調用,而不會緩存結果。this
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 變動狀態 state.count++ } } })
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
this.$store.commit('increment', 10)
其中,第一個參數是 state
,後面的參數是向 store.commit
傳入的額外的參數,即 mutation 的 載荷(payload) 。
store.commit
方法的第一個參數是要發起的 mutation
類型名稱,後面的參數均當作額外數據傳入 mutation
定義的方法中。
規範的發起 mutation
的方式以下:
// 以載荷形式 store.commit('increment',{ amount: 10 //這是額外的參數 }) // 或者使用對象風格的提交方式 store.commit({ type: 'increment', amount: 10 //這是額外的參數 })
額外的參數會封裝進一個對象,做爲第二個參數傳入 mutation
定義的方法中。
mutations: { increment (state, payload) { state.count += payload.amount } }
Action 異步方法(異步的更改狀態)
actions: { actionA ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('someMutation') resolve() }, 1000) }) } }
Action與mutation的區別
action提交的是mutation,而不是直接變動狀態
action能夠包含任意異步操做,而mutation只能且必須是同步操做
因爲使用單一狀態樹,應用的全部狀態會集中到一個比較大的對象。當應用變得很是複雜時,store 對象就有可能變得至關臃腫。
這時咱們能夠將 store 分割爲 模塊(module) ,每一個模塊擁有本身的 state
、 getters
、 mutations
、 actions
、甚至是嵌套子模塊——從上至下進行一樣方式的分割。
代碼示例:
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.state.a // -> moduleA 的狀態 store.state.b // -> moduleB 的狀態
歡迎各位大佬補充!