一、创建store
1、安装VUEX: npm install vuex@3.6.2 --save
2、npm i -S vuex-persistedstate (vuex持久化)
home.js 内容如下(列举home.js)
const state = {
companyInfo : [],
}
const mutations= {
SET_COMPANYINFO(state,res){
state.companyInfo = res
},
}
const actions = {
setCompanyInfo({ commit }, res) {
commit('SET_COMPANYINFO', res)
},
}
const getters = {
}
export default {
state,
actions,
mutations,
getters
}
store.js 内容如下
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import home from './modules/home'
import home from './modules/newHome'
import home from './modules/orderManage'
Vue.use(Vuex)
export default new Vuex.Store({
// strict:true,
plugins: [createPersistedState()],
modules: {
home,
newHome,
orderManage
}
})
main.js 内容如下(只显示了和store相关的部分内容)
import store from './vuex/store'
new Vue({
router,
store,
...App
}).$mount('#app')
二、使用store
触发 dispatch
this.$store.dispatch('setCompanyInfo', data)
**获取 state中的companyInfo **
this.$store.state.home.companyInfo
注意:所有的异步操作都要放在actions中,因为mutation 中不能做异步操作
三、批量使用Vuex的getter、state、actions
newHome.js:
const state = {
exitMerchantInfo:{},//开户信息
account:{},//开户状态信息
}
.
.
.
const actions = {
async setCompanyinfo({commit},id) {
const {data} = await getMerchantById(id)
commit('SET_COMPANY_INFO',data)
},
async setExitMerchantInfo({commit}){
const {data} = await getExitMerchantInfo()
commit('SET_EXIT_MERCHANT_INFO',data)
},
}
const getters = {
userAgreementFile(state){
if(location.host == 'app.96356.com'){
return `http://app.96365.com/mall/file/download/${state.account.userAgreementFileId}`
}else{
return `http://dev.96365.com/mall/file/download/${state.account.userAgreementFileId}`
}
},
llpayAgreementFile(state){
if(location.host == 'app.96356.com'){
return `http://app.96365.com/mall/file/download/${state.account.llpayAgreementFileId}`
}else{
return `http://dev.96365.com/mall/file/download/${state.account.llpayAgreementFileId}`
}
}
}
组件中使用
import {mapActions,mapState,mapGetters} from 'vuex'
computed:{
...mapState('newHome',['exitMerchantInfo','account']),
...mapGetters('newHome',['userAgreementFile','llpayAgreementFile'])
},
methods:{
...mapActions('newHome',['setCompanyinfo','setExitMerchantInfo']),
},