目录
三,为什么不直接使用this.$store.state.数据 this.$store.commit.方法 this.$store.dispath.方法
1.首先设置目录结构,条理清楚
扫描二维码关注公众号,回复:
14226685 查看本文章

2.设置index.js文件代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {mutations} from './mutations'
import actions from './actions'
import getters from './getters'
import Session from '../../../sessionStorage.js'
import eat from './modules/eat' //吃模块
import drink from './modules/drink' //喝模块
import play from './modules/play' //玩模块
import happy from './modules/happy' //乐模块
export default new Vuex.Store({
state: {
baseHttpUrl: '',//项目的请求地址
baseHttpFileUrl: '',//项目中下载文件的请求地址
apiBaseParam: {//请求的基本格式
"version": "",
"userId": '',
"token": Session.getItem('abc') ? Session.getItem('abc').token : "",
},
},
modules: {
eat,
drink,
play,
happy,
},
actions,
mutations,
getters
})
3.设置mutations.js文件代码
export const mutations = {
// 设置用户userId
PRO_SET_ID(state,value){
state.id = value;
},
// 设置类型
PRO_SET_TYPE(state,value){
state.Type = value;
},
// 设置faceLogo
PRO_SET_FACELOGO(state,value){
state.faceLogo = value;
},
}
4.设置actions.js文件代码
//请求的方法
import {
getEatMessage,
getPlayMessage,
} from '_ser/http.js'
export default {
//获取全部的吃信息,解构出来
getEatMessage({
commit,
state
},data) {
let param = {
page: 1,
pageSize: 10000,
}
return new Promise((resolve, reject) => {
getEatMessage(param).then(res => {
if (res.code == 200) {
//调用mutations中的方法,存储数据
commit('EAT_LIST', res.data)
}
resolve(res)
}).catch(err => {
reject(err)
})
})
},
...,
...,
...
}
5.在modules文件夹中,放置页面的vuex模块
/* 吃模块 */
const eat = {
state: {
time: 'oneDay', //一天
},
mutations: {
//宿管模块人员信息的时间
TIME(state, value) {
state.time = value
}
},
getters: {
getTime(state) {
return state.time
}
},
actions: {},
}
export default eat
页面中如何使用vuex呢
需要在页面中先引入
import { mapState, mapMutations, mapGetters, mapActions, Store } from "vuex";
一:使用state数据
通过this.getTime 即可获取数据
也可以使用mapStete获取数据
通过this.eat即可获取数据
二:使用mutatios和actions方法
通过this.getEatMessage() 即可使用actions方法
通过this.PRO_SET_ID() 即可使用mutations方法
三,为什么不直接使用this.$store.state.数据 this.$store.commit.方法 this.$store.dispath.方法
因为可能使用module,写在module中的state,actions,mutations,不是直接获取,中间需要再加上一层,但如果使用map...之类的,则无须考虑(mapState除外,需要加上)