问题
点击编辑按钮,会弹出下图的框。但是这两个下拉框有时候能显示数据有时候又不显示数据。下拉框的列表数据需要打开弹框的时候请求后端接口获取。但是页面刷新后,第一次打开弹框数据都能显示绑定上,猜测就是数据双向绑定的问题
页面显示
处理数据的代码
async renderForm () {
this.formLoading = true
let result = await this.$ajax({
method: 'get',
url: `/api/system/user/queryById`,
params: {
id: this.id
}
}).catch(result => {
this.formLoading = false
})
for (let attr in this.formValidate) {
this.$set(this.formValidate, attr, result.data[attr])
}
this.formValidate.password = this.defaultPassword
await this.tenantChange() //获取角色列表的数据
await this.areaChange('', true) //获取部门列表的数据
// debugger
// this.$nextTick(() => {
// this.$set(this.formValidate, 'roleId', result.data.roleId)
// this.$set(this.formValidate, 'departId', result.data.departId)
// })
setTimeout(() => {
this.$set(this.formValidate, 'roleId', result.data.roleId)
this.$set(this.formValidate, 'departId', result.data.departId)
this.formLoading = false
}, 200)
},
处理过程
使用debugger调试看一下执行顺序,都是先执行this.tenantChange()和this.areaChange(),再执行数据赋值this.$set(this.formValidate, 'roleId', result.data.roleId),害怕数据绑定失效,特意用了 $set 方法,还在一开始
formValidata对象不定义roleId和departId
for (let attr in this.formValidate) {
this.$set(this.formValidate, attr, result.data[attr])
}
为了测试是不是setTimeout里面函数是不是没有赋值上,在setTimeout函数之前,对数据赋值空数组,this.formValidate.roleId=[],发现如果页面值没有显示,则这个this.formValidate.roleId依旧数据为空。
使用了以下几种方法都没有用。。
- 使用v-if方法,销毁dom的方法重新绑定数据,
- 对select 组件进行key绑定,每次打开弹框都自增key
- 怀疑是不是awit没有写好,就把
this.tenantChange()和this.areaChange()全部改写在ajax的then函数里,但是没啥用。 - 在数据获取后,使用 $nextTick 方法再重新给值赋值也没有用,但是使用setTimeOut方法,延迟2秒赋值似乎有效果
最后解决方法
在数据复制前,把这个值从这个对象里删除
delete this.formValidate.roleId
delete this.formValidate.departId