请求数据
作为前端,首先要从请求数据开始:
定义服务
定义一个服务并导出:
import axios from "axios";
const service = axios.create({
baseURL: "/your-api/",
timeout: 0
});
// 请求拦截器
service.interceptors.request.use(
(config: any) => {
return config;
},
(error: any) => {
console.error(error);
return Promise.reject(error);
}
);
// 添加响应拦截器
service.interceptors.response.use(
(response: any) => {
return Promise.resolve(response.data);
},
(error: any) => {
console.error(error);
return Promise.reject(error);
}
);
export default service;
服务具体化
export const getxxx = () => {
return service({
url: '/mydata',
method: 'post',
headers: {
'Content-type': 'multipart/form-data'
}
});
};
定义actions
const actions = {
setxxx({commit}:any){
return new Promise((resolve, reject) => {
getmydata().then( (res:any) => {
}
commit('setAppState',{key:'mydata',value:res})
}).catch(err => {
reject()
});
});
}
定义mutations:
const mutations = {
setAppState(state: any, data: { key: string; value: any }) {
state[data.key] = data.value;
}
};
定义state数据源:
const state = {
mydata:[]
};
派遣获取数据的任务:
this.$store.dispatch('app/setAllTobaccoInfos');//actions
登记你的state数据源:
import { namespace } from "vuex-class";
const appStore = namespace("app");
export default class Home extends Vue {
@appStore.State("mydata") private mydata: any;
}
登记你的mutations,用来操作数据
@appStore.Mutation("setAppState") private setAppState: any;
定义Watch函数,实时监控数据变化,实现响应式:
@Watch("mydata", { immediate: true })
private onmydataChange(data: any) {
if (data) {
} else {
}
}
当你接收到通过网络请求到的数据后,提交mutations,会触发vue更新你的数据并且根据响应式原理改变ui里的数据。(下面的代码出现在了actions里面,由此可知数据流成一个圈)
commit('setAppState',{key:'mydata',value:res})