Vue.js 动态映射 JSON 到 Class 而无需 vue.Set 或在 Vuex store 中直接赋值
Vue.js dynamically Map JSON to Class without vue.Set or direct assignment in Vuex store
这是一个简单的问题:"Can I map a json response to a class without specifically enumerating the fields, either with vue.set, or by passing parameters to the class, and directly assigning them?"在我看来这是可能的。
在 React 中,我可以将数据映射到 class。
-谢谢
所以:
a) 我可以在 vue/vuex 中执行地图吗? (假设语法正确?)
b) 我是坚持使用 vue.set 还是手动分配?
c) 如果没有,是否有比 Vue-Model 更好的包?
谢谢
返回的数据:
{
abc: "Some Text",
def: 9999.999,
ghi: false
}
需要的字段集:
function anItem(payload){
this.abc = "";
this.def = 0;
this.ghi = false;
this.notices = [];
this.selected = false;
this.is_updating = false;
}
突变体
const mutations = {
setStuff (state, payload) {
/*this.state.myList.items = payload;*/ <- this works, of course.
this.state.mylist.items = payload.map(a => new anItem(a)) <-- syntax here?
},
};
您可以在构造对象时使用参数作为初始值:
function anItem(payload){
this.abc = payload.abc; // changed this line
this.def = payload.def; // changed this line
this.ghi = payload.ghi; // changed this line
this.notices = [];
this.selected = false;
this.is_updating = false;
}
然后,更改增变器以传递这样的参数:
const mutations = {
setStuff (state, payload) {
this.state.mylist.items = new anItem(payload);
},
};
这是一个简单的问题:"Can I map a json response to a class without specifically enumerating the fields, either with vue.set, or by passing parameters to the class, and directly assigning them?"在我看来这是可能的。
在 React 中,我可以将数据映射到 class。
-谢谢
所以: a) 我可以在 vue/vuex 中执行地图吗? (假设语法正确?) b) 我是坚持使用 vue.set 还是手动分配? c) 如果没有,是否有比 Vue-Model 更好的包?
谢谢
返回的数据:
{
abc: "Some Text",
def: 9999.999,
ghi: false
}
需要的字段集:
function anItem(payload){
this.abc = "";
this.def = 0;
this.ghi = false;
this.notices = [];
this.selected = false;
this.is_updating = false;
}
突变体
const mutations = {
setStuff (state, payload) {
/*this.state.myList.items = payload;*/ <- this works, of course.
this.state.mylist.items = payload.map(a => new anItem(a)) <-- syntax here?
},
};
您可以在构造对象时使用参数作为初始值:
function anItem(payload){
this.abc = payload.abc; // changed this line
this.def = payload.def; // changed this line
this.ghi = payload.ghi; // changed this line
this.notices = [];
this.selected = false;
this.is_updating = false;
}
然后,更改增变器以传递这样的参数:
const mutations = {
setStuff (state, payload) {
this.state.mylist.items = new anItem(payload);
},
};