javascript - 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 映射类型而无需重新创建它?
解决方案
您可以制作自己的映射器功能。
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)
})
})
推荐阅读
- c# - IsWithinDistance 无法翻译
- c - 在共享库上实现缺失符号
- javascript - 客户端 JavaScript 如何将用户 ID/密码发送到 Apache 服务器,以便解锁受 .htpasswd 保护的文件夹?
- java - Java JSoup 从网站抓取 img src 返回一个奇怪的 url
- html - 从 Web 应用程序打印 ZPL 命令文件
- swift - 即使数据已更新,tableviewdeleterows 也会导致应用程序崩溃
- sql - 触发器仅允许类大小/最大值为 2。处理某些值,但不处理其他值
- linux-kernel - 为什么在 kvm 中 MTF 位会在一段时间后重置?
- openapi - OpenApi 3 中的鉴别器
- git - `git rebase` 如何在后台工作?