Map.vue是為iview組件開(kāi)發(fā)的一個(gè)基于百度地圖的組件,實(shí)現(xiàn)了點(diǎn)是否在框內(nèi)的判斷,畫(huà)多邊形覆蓋物,添加自定義富文本標(biāo)記物等功能.
第一步:重構(gòu)自定義的富文本對(duì)象,設(shè)置為全局對(duì)象.
原代碼的富文本對(duì)象是聲明在addResource這個(gè)方法里面的,代碼結(jié)構(gòu)非常復(fù)雜,在beforeCreate這個(gè)鉤子函數(shù)里面申明為全局的,就可以多次復(fù)用,不需要重復(fù)聲明來(lái)了, 否則,每調(diào)用一次paintPolygon方法,都要重新聲明一次,非常麻煩,效率太低下.
原代碼是在父組件中處理好這個(gè)富文本對(duì)象需要的數(shù)據(jù),再把這些數(shù)據(jù)傳到富文本對(duì)象的構(gòu)造函數(shù)里面,重構(gòu)的處理方式,是將一整個(gè)數(shù)據(jù)對(duì)象(data對(duì)象)傳到對(duì)象的構(gòu)造函數(shù)里面,再根據(jù)需求,分解data對(duì)象來(lái)聲明對(duì)象的屬性(this._content | this._point | this._color等). 總結(jié)下來(lái),數(shù)據(jù)總是應(yīng)該在最靠近 使用數(shù)據(jù)的地方 進(jìn)行處理.
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下去除地圖點(diǎn)擊事件的冒泡
}else{
e.stopPropagation() // chrome下去除地圖點(diǎn)擊事件的冒泡
}
}
this._color = data['type'].color || "#5cadff" // 不同類(lèi)型的資源有不同的顏色,默認(rèn)顏色為#5cadff。
}
第二步:函數(shù)傳遞
需要為富文本添加電腦端的click事件和移動(dòng)端的touchstart事件.涉及到要操作父組件中的data數(shù)據(jù),所以采用將函數(shù)fun作為參數(shù)傳入
父組件請(qǐng)求回?cái)?shù)據(jù)再做處理,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("/")[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{
this.isExistImage = false
}
// 為資源添加附件
if (data["attachment"].length > 0){
this.isExistAttach = true
}else{
this.isExistAttach = false
}
// 顯示模態(tài)框
this.modal1 = true
})
})
在構(gòu)造函數(shù)中,這樣子處理
this._fun = e => {
fun(data)
if(typeof(e.preventDefault()) == 'function'){
e.preventDefault() // IE下去除地圖點(diǎn)擊事件的冒泡
}else{
e.stopPropagation() // chrome下去除地圖點(diǎn)擊事件的冒泡
}
}
最后,在合適的位置,添加事件
wrapDiv.addEventListener("touchstart", this._fun);
wrapDiv.addEventListener("click", this._fun);