Map.vue基于百度地图组件重构笔记分享

Map.vue是为iview组件开发的一个基于百度地图的组件,实现了点是否在框内的判断,画多边形覆盖物,添加自定义富文本标记物等功能.

第一步:重构自定义的富文本对象,设置为全局对象.

原代码的富文本对象是声明在addResource这个方法里面的,代码结构非常复杂,在beforeCreate这个钩子函数里面申明为全局的,就可以多次复用,不需要重复声明来了, 否则,每调用一次paintPolygon方法,都要重新声明一次,非常麻烦,效率太低下.

原代码是在父组件中处理好这个富文本对象需要的数据,再把这些数据传到富文本对象的构造函数里面,重构的处理方式,是将一整个数据对象(data对象)传到对象的构造函数里面,再根据需求,分解data对象来声明对象的属性(this._content | this._point | this._color等). 总结下来,数据总是应该在最靠近 使用数据的地方 进行处理.

window.ResOverlay = function(data, fun){ this._data = data this._content = data['type'].name + "|" + data['name'] this._point = new BMap.Point(data.coord[0], data.coord[1]) this._fun = e => { fun(data) if(typeof(e.preventDefault()) == 'function'){ e.preventDefault() // IE下去除地图点击事件的冒泡 }else{ e.stopPropagation() // chrome下去除地图点击事件的冒泡 } } this._color = data['type'].color || "#5cadff" // 不同类型的资源有不同的颜色,默认颜色为#5cadff。 }

第二步:函数传递

需要为富文本添加电脑端的click事件和移动端的touchstart事件.涉及到要操作父组件中的data数据,所以采用将函数fun作为参数传入

父组件请求回数据再做处理,rep.data.data.resources为data,fun就是 data => {}

this.$http.get('/api/search').then(rep => { this.$refs.main.addResource(rep.data.data.resources, data => { this.resourceName = data["name"] this.resourceType = data["type"].name this.resourceUpdata = data["uploader"] this.resourcePosition = data["coord"] console.log(data["attachment"]) let allList = [] data["attachment"].map(i => { let tempList = [] tempList.push(i) tempList.push(i.split("https://www.jb51.net/")[i.split("https://www.jb51.net/").length - 1]) allList.push(tempList) }) this.resourceDetial = allList // 为资源添加图像 for(let i=0; i<data["images"].length; i++){ this.resourceImage.push(data["images"][i]) } if (data["images"].length > 0){ this.isExistImage = true }else{ this.isExistImage = false } // 为资源添加附件 if (data["attachment"].length > 0){ this.isExistAttach = true }else{ this.isExistAttach = false } // 显示模态框 this.modal1 = true }) })

在构造函数中,这样子处理

this._fun = e => { fun(data) if(typeof(e.preventDefault()) == 'function'){ e.preventDefault() // IE下去除地图点击事件的冒泡 }else{ e.stopPropagation() // chrome下去除地图点击事件的冒泡 } }

最后,在合适的位置,添加事件

wrapDiv.addEventListener("touchstart", this._fun); wrapDiv.addEventListener("click", this._fun);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypsxs.html