首页 > 解决方案 > 我应该将一个数组返回给 Model 还是返回一个数组对象并通过 JS 更新 Model Vuejs?

问题描述

我在 Vuejs 中使用树视图,这个树视图包括父视图和子视图。每次更新,我调用 API 将数据更新到数据库我可以返回一个数组 Categories 以更新到模型类别或返回对象类别并使用 JS 代码更新模型类别。哪种情况更新,因为它有4种情况:更新不改变父母,改变父母,父母->孩子,孩子->父母。因此,为 Model 更新的代码 JS 比返回表更难:

// Update by return Array Categories
this.categories = response.data
this.active = []
this.editedCateory = null
this.$refs.form.reset()

//Update by use JS when return Object Category
this.updated = response.data
this.editedCateory.name = updated.name
this.editedCateory.url = updated.url
if(this.editedCateory.parent && !updated.parent)
{
    let oldparent = this.categories.filter(v=>v.id == this.editedCateory.parent)
    oldparent[0].children = oldparent[0].children.filter(v=>v.id != updated.id)
    updated = Object.assign({}, updated, {'children':[]})
    this.categories.push(updated)
}
else if(!this.editedCateory.parent && updated.parent)
{
    this.categories = this.categories.filter(v=>v.id != updated.id)
    let newparent = this.categories.filter(v=>v.id == updated.parent)
    newparent[0].children.push(updated)
}
else if(this.editedCateory.parent && updated.parent && (this.editedCateory.parent != updated.parent))
{
    let oldparent = this.categories.filter(v=>v.id == this.editedCateory.parent)
    oldparent[0].children = oldparent[0].children.filter(v=>v.id != updated.id)
    let newparent = this.categories.filter(v=>v.id == updated.parent)
    newparent[0].children.push(updated)
}
this.active = []
this.editedCateory = null
this.$refs.form.reset()

我正在编写 Vuejs,我想我应该使用 JS 更新模型,但它更复杂。

这种想法是对还是错?感谢观看

标签: javascriptvue.js

解决方案


也许在更新之后再次调用具有类别的 API 并再次设置类别是有意义的?如果数据发生变化,Vue 会重新渲染组件。使用 VUEX 似乎更容易。


推荐阅读