一、actions,mutations的使用。
这里我是把公共获取医院的方法和对应的值放在了vuex中方便后期调用。
1.在actions中进行异步的数据请求(axios接口我是自己重新封装过的)。
2.mutations中进行赋值(这里其实如果直接在mutation中进行请求也是可以的,但是一般不建议在mutation中只做一些逻辑处理)
import Vuex from 'vuex'
import Vue from 'vue'
import {CommonApi} from '../api/api.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
hospitalList: '',
},
mutations: {
hospitalList(state,res){
state.hospitalList = res;
},
},
actions: {//异步请求数据
getHospitalList({commit}) {//获取医院名称方法
CommonApi.getAllOrg().then(res => {
const {data, success} = res.data;
if (success) {
commit('hospitalList',data)
}
})
}
},
})
//组件中调用vuex
mounted() {
this.$store.dispatch('getHospitalList');//先派发异步事件
this.checkList = this.$store.state.hospitalList;
},
二、vuex刷新数据丢失问题。
1.在处理好vuex数据之后刷新页面会导致数据丢失。
2.在app.vue中进行localStorage存储并替换原来store中的空数据。
created(){
window.addEventListener("beforeunload",() => {
localStorage.setItem("store",JSON.stringify(this.$store.state))
})
let store = localStorage.getItem("store");
if(store){
this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("store"))));
}
}
另外,这是我的微信:ChenYuJ,前端新人一枚,希望有些共同前进的朋友。