1、模拟数据请求,例如我们与后端约定如下的数据格式
/*请求失败时*/
{
success:false,//请求失败
msg:"请求失败"
}
/*请求成功时*/
{
success:true,//表示请求成功
data:[{
id:1,
name:'Agwenbi'
},{
id:2,
name:'张三'
},{
id:3,
name:'李四'
}]
}
2、定义store等信息
import { createStore } from 'vuex'
export namespace GlobalStoreProps{
export interface DataProps{//成功时每一项的数据格式
id:number;
name:string;
}
export interface DataSuccess{//请求成功时的格式
success:boolean;
data:DataProps[]
}
export interface DataError{//请求失败时的格式
success:boolean;
msg:string;
}
export interface StoreProps{//定义store
data:DataProps[]
}
}
export default createStore<GlobalStoreProps.StoreProps>({
state: {
data:[]
},
mutations: {
setData(state,datas:GlobalStoreProps.DataProps[]){//设置的数据格式为DataProps[]
state.data = Object.assign([],datas);
}
}
})
3、xxx.vue中进行数据请求
<template>
<div>
{{JSON.stringify(getDatas)}}
</div>
</template>
<script lang="ts">
import { computed, defineComponent} from 'vue'
import { useStore } from 'vuex'
import {GlobalStoreProps} from '../../store'
export default defineComponent({
name:'vuexCom',
setup () {
let store = useStore<GlobalStoreProps.StoreProps>();
const getData = () => {
const resData = new Promise<GlobalStoreProps.DataSuccess | GlobalStoreProps.DataError>((resolve,reject) => {
setTimeout(() => {
//模拟数据请求
if(Math.random() - 0.5 > 0){
resolve({
success:true,//表示请求成功
data:[{
id:1,
name:'Agwenbi'
},{
id:2,
name:'张三'
},{
id:3,
name:'李四'
}]
});
}else{
resolve({
success:false,//请求失败
msg:"请求失败"
});
}
}, 2000);
});
return resData
}
getData().then(storeData => {
if(storeData.success){//数据请求成功时
store.commit('setData',(storeData as GlobalStoreProps.DataSuccess).data);
}else{//数据请求失败
console.log((storeData as GlobalStoreProps.DataError).msg);
}
});
const getDatas = computed(() => store.state.data);//使用data
return {
getDatas
}
}
})
</script>
<style scoped>
</style>