gpt4 book ai didi

javascript - VueJs Ajax 数据映射

转载 作者:搜寻专家 更新时间:2023-10-30 22:17:41 24 4
gpt4 key购买 nike

在 Vue 页面中,当 mounted() 事件被触发时,我调用了使用 Ajax 获取数据的方法。该代码使用新的 Pager 对象重新创建现有的 Pager,它必须在构造函数中传递所有参数以重建它。

如果我不这样做,vm.Pager 只是一个对象,没有一些需要的方法,并且无法通过传递给它的 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)
})
})

关于javascript - VueJs Ajax 数据映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com