const store = new Vuex.Store({
state,
getters,
mutations,
actions,
modules
})
const app = new Vue({
el: '#app',
// 把 store 對(duì)象提供給 “store” 選項(xiàng)媒怯,這可以把 store 的實(shí)例注入所有的子組件
store,
components: { Counter },
})
核心概念
-
state
作用:
存儲(chǔ)數(shù)據(jù)
state定義:
var state = {}
不使用vuex:
存儲(chǔ)需要使用的變量采幌,當(dāng)多個(gè)組件使用時(shí)惯悠,需要在不同組件中重復(fù)引用职车。
使用vuex:
在vuex對(duì)象中寫入state對(duì)象洲胖,并在vue根實(shí)例中引入vuex對(duì)象济榨,所有子組件都可以訪問。
使用方法:
this.$store.state.xx
-
Getters
作用:
定義多組件使用的計(jì)算屬性
getters定義:
傳入state作為第一個(gè)參數(shù)宾濒,可以選其他getters作為第二個(gè)參數(shù)
var getters = {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
不使用vuex:
當(dāng)多個(gè)組件使用同一個(gè)計(jì)算屬性時(shí)腿短,需要在多個(gè)組件中定義相同的計(jì)算屬性。
如:
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
使用vuex:
在vuex對(duì)象中寫入getters對(duì)象绘梦,所有子組件中可以使用橘忱。
使用方法:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
-
Mutation
mutation定義:
每個(gè) mutation 都有一個(gè)字符串的 事件類型 (type) 和 一個(gè) 回調(diào)函數(shù) (handler),接受state作為第一個(gè)參數(shù)卸奉,可傳入額外的參數(shù)钝诚。是同步事件不可在事件回調(diào)函數(shù)中寫入異步操作。
var mutations = {
increment (state, n) {
// 變更狀態(tài)
state.count += n
}
}
作用:
唯一修改store狀態(tài)的途徑是提交mutation中定義的事件榄棵,
相當(dāng)于把state中的數(shù)據(jù)當(dāng)成是可訪問不可修改的私有變量凝颇,而mutation是不可直接調(diào)用的公有方法,被當(dāng)成是事件的形式疹鳄,需要發(fā)射事件觸發(fā)相應(yīng)的回調(diào)函數(shù)拧略。
使用方法:
this.$store.commit('increment', n)
-
Actions
actions定義:
Action 函數(shù)接受一個(gè)與 store 實(shí)例具有相同方法和屬性的 context 對(duì)象,因此你可以調(diào)用 context.commit
提交一個(gè) mutation瘪弓,或者通過 context.state
和 context.getters
來獲取 state 和 getters垫蛆。
var actions = {
increment (context) {
context.commit('increment')
}
}
作用:
actions類似于mutations,不同的是actions提交的是mutation,而不是直接改變狀態(tài)袱饭,并且可以在actions內(nèi)部寫入異步操作川无。
使用方法:
this.$store.dispatch('increment')