这一次通过$emit实现子组件调用父组件的方法时,发现失效,耗了一个多小时,现在记录一下:
错误代码:
父组件
<pointDetail ref="pointDetail" v-if="pointDetailVisible" @set-hytabs="setHyTabs"
@point-detail-close="pointDetailClose" @handle-clear="handleClear" @load-circle="loadCircle" @pass-listquery2tmp="passListQuery2Tmp"/>
其中handleClear方法将子组件关闭
handleClear(){ ...this.pointDetailVisible = false; ... },
子组件
pointQuery(isPrice) { ... this.$emit('handle-clear'); ... gisDataQuery.getPointListNew(this.listQuery2).then((response) => {if (response.data) { ... that.$emit('set-hytabs',[]) let hyTabs = [] this.listQuery2.typeCode.forEach(code => { this.unitTypeOptions1.forEach(item => { if(item.itemCode == code){ hyTabs.push(item.itemName); } }); }); that.$emit('set-hytabs',hyTabs) this.loadData(pointList,[],centerPoint); if(pointList.length > 0){ that.$emit('pass-listquery2tmp',this.listQuery2) that.$emit('load-circle'); } } else { this.$message.warning("查询失败"); } }).catch((error) => { console.log(error); }); },
发现子组件的pointQuery方法调用后台接口后,4个that.$emit都失效。
通过百度发现一篇文章:
才发现在handleClear方法中将子组件关闭,导致事件被销毁。
解决办法:父组件handleClear方法中不关闭子组件,子组件执行所有that.$emit后关闭子组件。
handleClear(){ ... // this.pointDetailVisible = false; ... },
子组件最后再关闭子组件。
pointQuery(isPrice) { ... this.$emit('handle-clear'); ... gisDataQuery.getPointListNew(this.listQuery2).then((response) => { ... that.$emit('set-hytabs',[]) let hyTabs = [] this.listQuery2.typeCode.forEach(code => { this.unitTypeOptions1.forEach(item => { if(item.itemCode == code){ hyTabs.push(item.itemName); } }); }); that.$emit('set-hytabs',hyTabs) this.loadData(pointList,[],centerPoint); if(pointList.length > 0){ that.$emit('pass-listquery2tmp',this.listQuery2) that.$emit('load-circle'); } } else { this.$message.warning("查询失败"); } that.$emit('point-detail-close') }).catch((error) => { console.log(error); }); },
标签:...,listQuery2,handleClear,组件,失效,emit,hyTabs From: https://www.cnblogs.com/zwh0910/p/18196065