在vue里,組件之間的作用域是獨(dú)立的,父組件跟子組件之間的通訊可以通過prop屬性來傳參,但是在兄弟組件之間通訊就比較麻煩了。
比如A組件要告訴一件事給B組件,那么A就要先告訴他們的父組件,然后父組件再告訴B。
當(dāng)組件比較多,要互相通訊的事情很多的話,管理起來是非常累的事情。
而vuex正是為了解決這個問題,讓多個子組件之間可以方便的通訊。
1. vue store存儲commit 和dispatch的區(qū)別
1. 創(chuàng)建app.js文件
import Vue from 'vue'
import {SIDEBAR_TYPE} from "@/store/mutation-types"
const app = {
state: {
sidebar: {
opened: true,
withoutAnimation: false
}
},
mutations: {
SET_SIDEBAR_TYPE: (state, type) => {
state.sidebar.opened = type
Vue.ls.set(SIDEBAR_TYPE, type)
}
},
actions: {
setSidebar: ({ commit }, type) => {
commit('SET_SIDEBAR_TYPE', type)
}
}
}
export default app
1. dispatch:異步操作,調(diào)用的方法在actions中
存儲:
this.$store.dispatch('setSidebar', false)
取值:
this.$store.getters.targetUser;
2. commit:同步操作,方法定義在mutations中
存儲:
this.$store.commit('SET_SIDEBAR_TYPE', Vue.ls.get(SIDEBAR_TYPE, true))
取值:
this.$store.state.setTargetUser