首页 > 解决方案 > VueJs Ajax 数据映射

问题描述

在 Vue 页面中,我调用了一个调用,以在触发 mount() 事件时使用 Ajax 获取数据。该代码使用新的 Pager 对象重新创建现有的 Pager 对象,它必须传入构造函数中的所有参数才能重建它。

如果我不这样做, vm.Pager 只是一个 Object 并且没有一些需要的方法,并且无法通过传递给它的 prop 类型检查。

        axios.post("/Home/GetList", vm.Pager)
        .then(function (result)
        {
           var p = result.data.Pager;
           vm.Pager = new Pager(p.PageSize, p.CurrentRecord, p.TotalCount);
           // etc. (Pager has additional fields...)
           vm.ItemList = result.data.ListItems;        
        })
        .catch(function (error)
        {
            alert(error); 
        });

在 knockoutjs 中,有一个映射函数,您可以告诉它要映射哪些类型,而无需重新创建对象。这很方便,特别是对于更复杂或嵌套的 Ajax 数据。

有没有更好的方法在 Vue(或 javascript)中执行此操作,它从 Ajax 映射类型而无需重新创建它?

标签: javascriptajaxvue.js

解决方案


您可以制作自己的映射器功能。

methods: {
  mapTypesToData (responseData, map) {
     responseData.forEach((item, key) => {
       let mapperVal = map[key]
       if (typeof mapperVal === 'string') {
         this.$set(this, map[key], item)
       } else if (typeof mapperVal === 'function') {
         this.$set(this, key, map[key](item))
       }
     })
  }
}

然后在你的ajax请求中

        axios.post("/Home/GetList", vm.Pager)
        .then(function (result)
        {
          this.mapTypesToData(result.data, {
            ItemList: 'ListItems',
            Pager: (p) => new Pager(p.PageSize, p.CurrentRecord, p.TotalCount)
          })      
        })

推荐阅读