使用 vue + vuex + axios
代码如下:
let sexList = [// store 里的数据 { code: 0, sexText: '女', }, { code: 1, sexText: '男', } ] let clientList = [// index 页面里的数据 { name: '杨过', sexCode: 1, }, { name: '小龙女', sexCode: 0, } ] mounted() { this.$store.disptch('getSexList')// 获取性别列表 getClientList({data: 'clients'}).then((res) => { if(res.data.success) { this.clientList = res.data.data// 获取客户数据 }else { this.$message.error(res.data.message) } }).catch((err) => { console.log(err) }) }, watch: { clientList(val) {// 监听客户数据,遍历对比 sexList 的 sexCode,放到客户列表里 if(val && val.length > 0) { val.map((item) { this.$store.getters.sexList.map((sex_item) => { if(sex_item.sexCode == item.sexCode) { item.sexText = sex_item.sexText } }) }) } }, }
页面进入的时候并不能实现我想要的效果:监听客户数据 clientList,遍历对比 store 里的 sexList 的 sexCode,把性别 sexText 放到客户列表里
请问一下该怎么解决这个异步的问题?
![]() | 1 airyland 2018-11-21 00:36:10 +08:00 看文档,watch 设置 immediate: true |
![]() | 2 johnnyNg 2018-11-21 08:59:38 +08:00 via iPhone mark 一下,待会儿再看 |
![]() | 3 johnnyNg 2018-11-21 10:43:14 +08:00 ```js { created() { this.$store.dispatch('getSexList')// 获取性别列表 getClientList({data: 'clients'}).then((res) => { if(res.data.success) { this.clientList = res.data.data// 获取客户数据 }else { this.$message.error(res.data.message) } }).catch((err) => { console.log(err) }) }, computed: { myClientList() { if (this.$store.getters.sexList.length === 0 || this.clientList.length === 0) return [] return this.clientList.map((item) => ({ ...item, ...this.$store.getters.sexList.find(({code}) => code === item.sexCode ) })) } } } ``` |
![]() | 4 johnnyNg 2018-11-21 10:44:12 +08:00 语法高亮是怎么弄得,我发的 markdown 不支持? |