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