一、原理圖及作用
功能介紹:
簡單說就是Vue
項(xiàng)目中,各個(gè)組件間通信的一種框架
相較于之前的全局事件總線
,該框架更實(shí)用!
提高了代碼的復(fù)用率,把核心業(yè)務(wù)代碼,集中到store
中,這樣,一處實(shí)現(xiàn),處處調(diào)用。
原理:VC 調(diào)用 actions
actions調(diào)用mutations
mutations調(diào)用state
VC讀取state
完美閉環(huán)!
二、核心代碼
安裝插件
npm i vuex@3 Vue2的項(xiàng)目,安裝Vuex3
npm i vuex@4 Vue3的項(xiàng)目,安裝Vuex4
vue_test/src/store/index.js
//該文件用于創(chuàng)建vuex中最為核心的store
//引入Vue
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//準(zhǔn)備actions 用于響應(yīng)組件中的動(dòng)作
const actions = {
jia(context, value) {
console.log('actions中的jia被調(diào)用了')
context.commit('JIA', value)
},
jian(context, value) {
console.log('actions中的jian被調(diào)用了')
context.commit('JIAN', value)
},
jiaOdd(context,value){
console.log('actions中的jiaOdd被調(diào)用了')
if(context.state.sum % 2){
context.commit('JIA',value)
}
},
jiaWait(context,value){
console.log('actions中的jiaWait被調(diào)用了')
setTimeout(()=>{
context.commit('JIA',value)
},500)
}
};
//準(zhǔn)備mutations 用于操作數(shù)據(jù)state
const mutations = {
JIA(state,value){
console.log('mutations中的JIA被調(diào)用了')
state.sum += value
},
JIAN(state,value){
console.log('mutations中的JIAN被調(diào)用了')
state.sum -= value
}
};
//準(zhǔn)備state 用于存儲數(shù)據(jù)
const state = {
sum: 0 //當(dāng)前的和
};
//創(chuàng)建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
});
main.js
這樣配置后,在所有的VC
中就可以使用這個(gè)store
了。
import store from './store/index'
//創(chuàng)建vm,整個(gè)項(xiàng)目就這1個(gè)vm,其他的都是vc組件
new Vue({
el:"#app",
render: h => h(App),
store,
beforeCreate() {
Vue.prototype.$bus = this; //安裝全局總線
}
});
三、使用案例
1、讀取store
中的變量值
{{$store.state.sum}}
2、VC
中修改store
中的變量值
方式1:
this.$store.dispatch('jia',this.n)
方式2:
this.$store.commit('JIA',this.n)
四、詳細(xì)說明
1、類比Java
的mvc
我們可以看到,store
中,主要有三個(gè)對象
actions 類似于Java的controller接口,業(yè)務(wù)邏輯
mutations 類似于Java的service層,修改數(shù)據(jù)
state 類似于Java的dao層,存儲數(shù)據(jù)
2、store
中各對象詳解actions
對象中的函數(shù)參數(shù):context
:
有這個(gè)context
,那么,actions
中的函數(shù),就可以調(diào)用actions
中其它的函數(shù)
不一定,actions
就要進(jìn)入mutations
步驟。value
:
就是調(diào)用時(shí)傳入的具體值。文章來源:http://www.zghlxwxcb.cn/news/detail-825785.html
3、mutations
對象中的函數(shù)參數(shù):state
:就是store
中的state
。value
:調(diào)用時(shí)傳入的具體參數(shù)值。文章來源地址http://www.zghlxwxcb.cn/news/detail-825785.html
到了這里,關(guān)于Vue2:組件間通信框架Vuex的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!