在使用Vuex之前需要使用Vue聲明組件
- Vue.use(Vuex)
- let store = new Vuex.store({
- state,// Vuex中保存數據
- mutations, // 對Vuex中的state中的數據進行操作
- actions, //使用 commit() 對mutations操作
- getters //類似於computed計算屬性
- })
- new Vue({ store })
需要使用在Vue中綁定 store
Store聲明之後回創建一個 $store對象 $store對象中有 Vuex中的state對象 以及 getter對象 可通過$store.state 或者$store.getter 的方法調用
actions對象 需要通過dispatch方法調用 如
methods:{
add(){ dispatch("addcount","可以傳輸的數據") }
}
vuex中的actions 對象
let actions = {
addcount({commit,state},val){
commit( "addcounts",val )
}
}
Vuex中的mutations 對象
let mutations = {
addcounts(state,val){ //
state.count += val
}
}
Vuex中的state 對象
let state = {
count:0,
}
Vuex中的getters對象 使用方法
let getters = {
decrement(state){
state.count
}
}
調用在對應vue組件中
computed:{
dec(){
return this.$store.getters.decrement; //在getters中定義的函數不需要調用 因爲爲getter方法 在數據讀取時會自動調用
}
}