溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Map.vue基于百度地圖組件重構筆記分享

發(fā)布時間:2020-08-20 11:02:15 來源:腳本之家 閱讀:137 作者:tonydandelion2014 欄目:web開發(fā)

Map.vue是為iview組件開發(fā)的一個基于百度地圖的組件,實現(xiàn)了點是否在框內的判斷,畫多邊形覆蓋物,添加自定義富文本標記物等功能.

第一步:重構自定義的富文本對象,設置為全局對象.

原代碼的富文本對象是聲明在addResource這個方法里面的,代碼結構非常復雜,在beforeCreate這個鉤子函數(shù)里面申明為全局的,就可以多次復用,不需要重復聲明來了, 否則,每調用一次paintPolygon方法,都要重新聲明一次,非常麻煩,效率太低下.

原代碼是在父組件中處理好這個富文本對象需要的數(shù)據(jù),再把這些數(shù)據(jù)傳到富文本對象的構造函數(shù)里面,重構的處理方式,是將一整個數(shù)據(jù)對象(data對象)傳到對象的構造函數(shù)里面,再根據(jù)需求,分解data對象來聲明對象的屬性(this._content | this._point | this._color等). 總結下來,數(shù)據(jù)總是應該在最靠近 使用數(shù)據(jù)的地方 進行處理.

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。
} 

第二步:函數(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
  })
 })

在構造函數(shù)中,這樣子處理

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);

本文已被整理到了《Vue.js前端組件學習教程》,歡迎大家學習閱讀。

關于vue.js組件的教程,請大家點擊專題vue.js組件學習教程進行學習。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI