Vuex
主要有5大属性:modules、state、mutations、actions、getters,分别介绍
modules的作用:
主要是引入其它模块定义的Vuex,使用方法和Vuex的index.js一样,只是需要加上模块名作为路径去选择哪个模块的属性
例子
定义一个模块名称为global 的Vuex文件,也是5大属性;
第一步:引入到index.js文件中,引入方式import global from “./global”;
第二步:在index.js的modules属性中注册,注册方式modules: {global:global},
.vue文件使用Vuex
index.js文件定义的Vuex属性的使用
import { mapState,mapGetters,mapMutations,mapActions } from ‘vuex’;
state的使用
computed: {
//状态管理操作
…mapState({
userInfo: state => state.userInfo,//index.js文件的使用
userInfo: state => state.global.userInfo,//global.js文件的使用
})
…mapGetters({
conversationList:“conversationList”,//index.js文件的使用
conversationList:“timConversation/conversationList”,//global.js文件的使用
}),
},
Mutations,Actions的使用
methods: {
…mapMutations({
conversationMes: “getMessageList”,//index.js文件的使用
conversationMes:“global/getMessageList”,//global.js文件的使用
}),
…mapActions({
conversationMes: “getMessageList”,//index.js文件的使用
conversationMes:“global/getMessageList”,//global.js文件的使用
}),
},
完整的Vuex的index.js文件
import Vue from "vue";
import Vuex from "vuex";
import global from "./global";
import timUser from './tim/timUser';
import timConversation from './tim/timConversation';
import timGroup from './tim/timGroup';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
global,
timUser,
timConversation,
timGroup,
},
state: {
hasUserInfo: false,// 是否有登錄
userInfo: {// 用户信息
nickName: "这是昵称哦",// 昵称
avatarUrl: "",// 头像
phone:0,
},
token:'',
notToken:'',
// 页面缓存,需要根据当前路由的路径转化成页面的name
pageCacheList: [],
equipmentInfo:{},//储存设备信息
jingweidu:{
longitude:0,
latitude:0,
},// 经纬度
area:{},//当前所在地区信息
shop_id:0,//商铺id
chooseShopdata:{},//存储选择城市获取的商家数据
allCitys:[],//全部城市省市区信息
selectedMusic:[],//已选择的音乐
beizhu:{},//用户的备注和标签
},
mutations: {
// 更新用户信息
'USERINFO': (state, userInfo) => {
state.userInfo = userInfo.res
},
// 更新用户登錄狀態
'HASUSERINFO': (state, hasUserInfo) => {
state.hasUserInfo = hasUserInfo.res
},
// notToken
'NOTTOKEN': (state, notToken) => {
state.notToken = notToken.res
},
// 更新token
'TOKEN': (state, token) => {
state.token = token.res
},
// 更新状态栏高度
'EQUIPMENTINFO': (state, equipmentInfo) => {
state.equipmentInfo = equipmentInfo.res
},
// 更新经纬度信息
"JINGWEIDU":(state,jingweidu)=>{
state.jingweidu=jingweidu.res
},
// 更新用户当前所在地区
'AREA': (state, area) => {
state.area = area.res
},
// 更新商铺id
'SHOP_ID': (state,shop_id) => {
state.shop_id = shop_id.res
},
// 更新选择城市的商家信息
'SHOPDATA': (state,shopdata) => {
state.chooseShopdata = shopdata.res
},
// 更新全部城市省市区信息
'ALLCITYS': (state,dataCity) => {
state.allCitys = dataCity.res
},// 更新全部城市省市区信息
'BEIZHU': (state,data) => {
state.beizhu = data.res
},
},
actions: {
// actions可以使用mutations方法
getVip1 ({ state, commit, rootState },data) {
commit('USERINFO')
},
getVip2 ({ state, commit, rootState },data) {
commit('EQUIPMENTINFO')
}
},
//可以认为【getters】是Vuex的计算属性,可以处理每个vue文件需要state属性不同需求逻辑。单独看另外的博客getters的介绍
getters: {
conversationList(state){
console.log("是否触发此函数")
return state;
}
},
//conversationList函数的返回值需要使用到了,才会触发到该函数
});