V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
test4zhou
V2EX  ›  前端开发

vue 的异步数据遍历

  •  
  •   test4zhou · 2018-11-20 22:48:59 +08:00 · 2889 次点击
    这是一个创建于 1956 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用 vue + vuex + axios

    代码如下:

    let sexList = [// store 里的数据
      {
        code: 0,
        sexText: '女',
      },
      {
        code: 1,
        sexText: '男',
      }
    ]
    
    let clientList = [// index 页面里的数据
      {
        name: '杨过',
        sexCode: 1,
      },
      {
        name: '小龙女',
        sexCode: 0,
      }
    ]
    
    mounted() {
      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)
      })
    },
    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 放到客户列表里

    请问一下该怎么解决这个异步的问题?

    5 条回复    2018-11-21 13:44:34 +08:00
    airyland
        1
    airyland  
       2018-11-21 00:36:10 +08:00
    看文档,watch 设置 immediate: true
    johnnyNg
        2
    johnnyNg  
       2018-11-21 08:59:38 +08:00 via iPhone
    mark 一下,待会儿再看
    johnnyNg
        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 )
    }))
    }
    }
    }

    ```
    johnnyNg
        4
    johnnyNg  
       2018-11-21 10:44:12 +08:00
    语法高亮是怎么弄得,我发的 markdown 不支持?
    test4zhou
        5
    test4zhou  
    OP
       2018-11-21 13:44:34 +08:00
    @johnnyNg 开头应该是```javascript
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2953 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 08:24 · PVG 16:24 · LAX 01:24 · JFK 04:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.