vuex是什麽?怎麽用,例子
什麽是vuex?
官方的解釋是:Vuex 是一個專為 Vue.js 應用程序開發的狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
為什麽要用vuex?
-
對於父子組件之前的通信,父組件通過porps傳遞到子組件,子組件通過$emit發送事件到父組件;父組件還可以通過ref的方式拿子組件的值並共享;
-
對於組件與組件之間的通信,可以new一個新的Vue實例,專門用來做event bus進行通信。怎麽用?
- 當多個組件之間共享一個狀態時,event bus可能就變成亂了
怎麽用?
組件A的js中: this.$store.dispatch(‘get_beforeVote_params‘,this.dynamicValidateForm.email); //設值
組件B的template中:<p>{{‘beforeVoteParams:‘+$store.state.vote.beforeVoteParams}}</p> //引用值
組件B的js中: 如果沒有引用這句話:import store from ‘@/store/index‘ 就:this.$store.state.vote.beforeVoteParams 直接用;
如果引用了這句話:import store from ‘@/store/index‘ 就:store.state.vote.beforeVoteParams
1)入口文件中要引入同級目錄下的:import store from ‘./store‘ //import store from ‘./store‘/index.js index.js是省略的寫法
vue用的版本是:"vue": "^2.3.3",
vuex用的版本是:"vuex": "^2.3.1",
並且要加入進來:
new Vue({
router,
store,
axios,
template: ‘<App/>‘,
components: { App }
}).$mount(‘#app‘);
2)目錄如下:
3)在index.js中:
import Vue from ‘vue‘;
import Vuex from ‘vuex‘;
import getters from ‘./getters‘;
import user from ‘./modules/user‘;
import permission from ‘./modules/permission‘;
import vote from ‘./modules/vote‘;
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
user,
permission,
vote
},
getters
});
export default store
4)在getter.js中:
我們可以在store
中定義getters
,第一個參數是state;
傳參:定義的Getters
會暴露為store.getters
對象,也可以接受其他的getters
作為第二個參數;
const getters = {
paramsself:state =>state.vote.beforeVoteParams,
};
export default getters
頁面上可以這麽用:<p>{{‘paramsself:‘+$store.getters.paramsself}}</p>
5)在vote.js中:
const vote = {
state: {
beforeVoteParams : ‘‘,
index:"queryHoldVolume11115"
},
mutations: {
GET_BEFOREVOTE_PARAMS:(state,item)=>{
state.beforeVoteParams = item;
}
},
actions: {
get_beforeVote_params:({commit},item)=>{
commit(‘GET_BEFOREVOTE_PARAMS‘,item)
},
}
};
export default vote;
差不多就是這麽用的。
state, <!--狀態--> getters, <!-- 狀態的計算屬性 --> mutations, <!-- 用於改變狀態 --> actions, <!-- 可包含異步操作的mutation -->
3.mapGetters
mapGetters
輔助函數僅僅是將store
中的getters
映射到局部計算屬性中,用法和mapState
類似
此圖來源別處;
vuex是什麽?怎麽用,例子