Map.vue基于百度地圖組件重構筆記教程

Map.vue基于百度地圖組件重構筆記教程

Map.vue是為iview組件開發的一個基于百度地圖的組件,實現了點是否在框內的判斷,畫多邊形覆蓋物,添加自定義富文本標記物等功能.
第一步:重構自定義的富文本對象,設置為全局對象.
原代碼的富文本對象是聲明在addResource這個方法里面的,代碼結構非常復雜,在beforeCreate這個鉤子函數里面申明為全局的,就可以多次復用,不需要重復聲明來了, 否則,每調用一次paintPolygon方法,都要重新聲明一次,非常麻煩,效率太低下.
原代碼是在父組件中處理好這個富文本對象需要的數據,再把這些數據傳到富文本對象的構造函數里面,重構的處理方式,是將一整個數據對象(data對象)傳到對象的構造函數里面,再根據需求,分解data對象來聲明對象的屬性(this._content | this._point | this._color等). 總結下來,數據總是應該在最靠近 使用數據的地方 進行處理.

window.ResOverlay = function(data, fun){
this._data = http://www.zuomama.com/qiaomen/youxi/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 = http://www.zuomama.com/qiaomen/youxi/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("/")[i.split("/").length - 1])
allList.push(tempList)
})
this.resourceDetial = allList
// 為資源添加圖像
for(let i=0; i
this.resourceImage.push(data["images"][i])
}
if (data["images"].length > 0){
this.isExistImage = true
}else{
【Map.vue基于百度地圖組件重構筆記教程】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);

經驗總結擴展閱讀