1、使用场景
如果在一个项目开发中频繁的使用组件传参的方式来同步data
中的值,一旦项目变得很庞大,管理和维护这些值将是相当棘手的工作。Vue
为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX
。在具有VueX
的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。
2、entry下index.js中内容
import Vue from 'vue';
import storeConfig from 'store/index.js';
import Vuex from 'vuex';
//挂载Vuex
Vue.use(Vuex);
//创建VueX对象
const store = new Vuex.Store(storeConfig);
//将store挂载到当前项目vue实例当中去
new Vue({
el: "#app",
router,
store,
});
3、store下的index.js
import Socket from './socket';
import api from './api';
export default {
state: {
userInfo: null,
socket: new Socket(),
socketMessage: null,
addressBook: null,
processWarningEventList: null,
},
//mutations是操作state数据的方法的集合,比如对该数据的修改、增加、删除等等。
mutations: {
setSocketMessage(state, socketMessage) {
state.socketMessage = socketMessage;
},
setaddressBook(state, addressBook) {
state.addressBook = addressBook;
},
//预警响应列表数据
setProcessWarningEventList(state, processWarningEventList) {
state.processWarningEventList = processWarningEventList;
}
},
//可以对state中的成员加工后传递给外界
getters:{
nameInfo(state){
return "用户:"+state.userInfo
},
useInfo(state,getters){
return getters.nameInfo+'地址:'+state.addressBook
}
}
//actions专门进行异步操作,最终提交mutation方法。
actions: {
startSocket(context) {
let phone = context.state.userInfo.phone;
context.state.socket.connectSocket(phone, context);
},
//存储响应事件列表信息
onSocketMessage(context) {
console.log(context.state.socketMessage, '123');
// dispatch:异步操作的存储(用getters.queryWarningEvent取值)
context.dispatch('queryWarningEvent');
},
//存储操作人员信息
async queryAddressBook({ commit }) {
const res = await api.getAddressBook();
let data = res.data;
// commit:同步操作的存储(用state.setaddressBook取值)
commit('setaddressBook', data);
},
//预警响应
async queryWarningEvent({ commit, state }) {
let resProcess = '';
resProcess = await api.queryProcessWarningEvent();
commit('setProcessWarningEventList', resProcess );
},
}
};
4.在组件中使用vuex
1.state在标签中使用
<h1>{{ $store.state.userInfo}}</h1>
2.state在方法中使用
computed: {
processEmergencyEventList() {
return this.$store.state.processEmergencyEventList;
},
},
3.mutation在组件中调用
this.$store.commit('setaddressBook')
4.mutation在提交某个mutation时需要携带一些参数给方法使用。
this.$store.commit('setaddressBook',1)//单个值提交
this.$store.commit('setaddressBook',{tel:12199999999,name:'Tom'})//多个参数时,放在对象中提交
5.getters在组件中使用
this.$store.getters.useInfo
6.action在组件中调用
this.$store.dispatch('queryWarningEvent')