js模板字符串中使用循环遍历数据

原创
07/24 09:59
阅读数 2K

模板字符串可以嵌入变量, 模板字符串使用反引号 (` `) 来代替普通字符串中的用双引号和单引号。模板字符串可以包含特定语法(${expression})的占位符。我们经常用的是`my name is ${name}`,如果是下面的格式,怎么处理比较方便

如果resultList[j] 是下面的内容

{
  title:"标题",
  content:[
   {name:"名称1",value:"10",unit:"k"},
   {name:"名称2",value:"12",unit:"k"}
  ]
}
          let labelContent = `
          <div class="mapLabel">
             <div class="labelTitle">${resultList[j].title}</div>
             ${resultList[j].content.map(item=>{
               return `<div>${item.name}:${item.value} ${item.unit}</div>`
             }).join("")}
          </div>
          `

上面的html片段是用在高德地图的marker 的label

<template>
  <div :style="myStyle" :class="isActive?'active':''">
    <div :id="`${config.id}`" class="map"
      :style='`width:${myStyle.width};height:${myStyle.height}`'></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
  props: {
    isAdd: {
      type: Boolean,
      default: false,
    },
    isActive: { type: Boolean, default: false },
    componentData: Object,
    myStyle: {
      type: Object,
      default: () => ({
        width: "100%",
        height: "100%",
      }),
    },
    config: {
      type: Object,
      default: () => ({
        id: "GDMap1",
      }),
    },
  },
  data() {
    return {
      siteMarkers: [],
      PersonMarkers: [],
      polyline:[],
      linesColors: {
        PT001: "red",
        PT002: "#e40faf",
        PT003: "#f49814",
        PT004: "#f44414",
        PT005: "#f4c714",
        PT006: "#f7f943",
      }, 

      markers: [],
      plugins: [
        "AMap.OverView",
        "AMap.MouseTool",
        "AMap.PolyEditor",
        "AMap.RectangleEditor",
        "AMap.PlaceSearch",
        "AMap.DistrictLayer",
        "AMap.CustomLayer",
        "AMap.Autocomplete",
        "AMap.Geocoder",
        "AMap.Geolocation",
        "AMap.CitySearch",
        "AMap.Marker",
        "AMap.ToolBar",
        "AMap.Scale",
      ],
      GDMap: null,
      mapData: {
        zoom: 7,
        center: [119, 38],
        data: [],
      },
    };
  },

  created() {
    console.log(this.config);
    this.$emit("saveConfig", this.config);
    this.mapData = this.componentData.mapData;
  },
  mounted() {
    this.showMap();
  },
  methods: {
    showMap() {
      AMapLoader.load({
        key: "0fa0370a30756563a2b12870585ee21b",
        version: "1.4.4",
        plugins: this.plugins,
        AMapUI: {
          version: "1.1",
          plugins: ["overlay/SimpleMarker"],
        },
        Loca: {
          version: "1.3.2",
        },
      }).then((AMap) => {
        this.GDMap = new AMap.Map(this.config.id, {
          resizeEnable: true,
          // zoom: this.mapData.zoom,
          // center: this.mapData.center,
          mapStyle: "amap://styles/d01ce3d81c8f3eff92a57c5e44f9b374",
        });
        // this.GDMap.setCenter(this.mapData.center);
        // this.GDMap.setZoom(this.mapData.zoom);
        this.GDMap.on("complete", () => {
          this.GDMap.addControl(new AMap.ToolBar());
          AMapUI.loadUI(["control/BasicControl"], (BasicControl) => {
            this.GDMap.addControl(
              new BasicControl.Zoom({
                position: "lt",
                showZoomNum: true,
                theme: "blue",
              })
            );
          });
          this.showSiteMarker();
          this.showPersonMarker();
          this.drawLine();
        });
      });
    },
    showSiteMarker() {
      let siteMarkerArray = this.mapData.dataObj.sitePointData;
      if (this.siteMarkers.length) {
        this.GDMap.remove(this.siteMarkers);
      }
      for (let i = 0; i < siteMarkerArray.length; i++) {
        let resultList = siteMarkerArray[i].resultList;
        let icon
        if(siteMarkerArray[i].typeCode == "001"){
          icon = require("@/assets/imgs/site_input.png")
        }else if(siteMarkerArray[i].typeCode == "002"){
          icon = require("@/assets/imgs/site_distribution.png")
        }else if(siteMarkerArray[i].typeCode == "003"){
          icon = require("@/assets/imgs/site_custom.png")
        }
        for (let j = 0; j < resultList.length; j++) {
          let marker = new AMap.Marker({
            icon:icon,
            position: resultList[j].position,
            map: this.GDMap,
          });
          let labelContent = `
          <div class="mapLabel">
             <div class="labelTitle">${resultList[j].title}</div>
             ${resultList[j].content.map(item=>{
               return `<div>${item.name}:${item.value} ${item.unit}</div>`
             }).join("")}
          </div>
          `
          marker.setLabel({
            offset: new AMap.Pixel(40, 5),
            content:labelContent
          });
          this.siteMarkers.push(marker);
        }       
      }
    },
    showPersonMarker(){
      let personMarkerArr = this.mapData.dataObj.userData
      if (this.PersonMarkers.length) {
        this.GDMap.remove(this.PersonMarkers);
      }
      personMarkerArr.forEach((item) => {
        let marker = new AMap.Marker({
          icon: require("@/assets/imgs/site_custom.png"),
          position: item.position,
          map: this.GDMap,
        });
        marker.setLabel({
          offset: new AMap.Pixel(40, 5),
          content: "<div class='personMapLabel'>" + item.label + "</div>",
        });
        this.PersonMarkers.push(marker);
      });

    },
    drawLine(){
      let lineArr = this.mapData.dataObj.pipeData
      for(let i=0;i<lineArr.length;i++){
        let color = this.linesColors[lineArr[i].pipenetworkTypeCode] 
        lineArr[i].data.forEach(path=>{
          let polyline = new AMap.Polyline({
            path: path,
            // isOutline: true,
            // outlineColor: color,
            // borderWeight: 2, // 线条宽度,默认为 1        
            strokeColor: color,
            strokeWeight:3,
            lineJoin: "round", // 折线拐点连接处样式
          });  
          this.polyline.push(polyline)
          this.GDMap.add(polyline);
        })
      }
    }
  },
  watch: {  
    componentData: {
      handler(newValue) {
        console.log("watch 地图");
        this.mapData = newValue.mapData;
        this.showSiteMarker();
        this.showPersonMarker();
        this.drawLine();
      }
    },
    config: {
      handler(newValue) {
        console.log(newValue);
      },
      deep: true,
      // immediate:true
    },
  },
};
</script>

<style scoped>
/deep/.amap-ui-control-theme-blue .amap-ui-control-zoom {
  border-color: #6d87ae;
  margin-top: 60px;
  margin-left: -10px;
}

/deep/.amap-ui-control-theme-blue .amap-ui-control-zoom a,
.amap-ui-control-theme-blue .amap-ui-control-zoom-num {
  background-color: #0d203e;
  border-bottom-color: #6380b5;
  color: #6d87ae;
}

/deep/.amap-ui-control-zoom-num {
  background-color: #0d203e;
  border-bottom-color: #6380b5;
  color: #6d87ae;
}

/deep/.amap-pancontrol {
  width: 52px;
  height: 52px;
  background: url(../../../assets/imgs/map_view.png) 0 -140px;
  background-image: url(../../../assets/imgs/map_view.png);
  background-position-x: 0px;
  background-position-y: -140px;
  background-size: initial;
  /* background-repeat-x: initial;
        background-repeat-y: initial; */
  background-attachment: initial;
  background-origin: initial;
  background-clip: initial;
  background-color: initial;
  position: absolute;
}

/deep/.amap-zoomcontrol {
  width: 24px;
  position: absolute;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  display: none;
}

/deep/.amap-locate {
  width: 22px;
  height: 22px;
  margin-top: 5px;
  background: url(../../../assets/imgs/map_view.png) -130px -185px;
  cursor: pointer;
}
/deep/.amap-marker-label { 
  /* background: rgba(0,45,105,0.7); */
  background:transparent;
  color: #fff;
  /* padding: 10px; */
  padding:0;
  border-radius: 3px;
  border: none;
  /* border-top:2px solid #0096ff;
  box-shadow: inset 2px 2px 10px rgba(2013,244,255,0.1); */
}
/deep/.mapLabel {
  background: rgba(0,45,105,0.7);
  padding:10px;
  border-top:2px solid #0096ff;
  box-shadow: inset 2px 2px 10px rgba(2013,244,255,0.1);
}

/deep/.mapLabel div{line-height:25px;color:#8abaf9;font-size:14px;}
/deep/.mapLabel .labelTitle{color:#d5f4ff;font-size:16px;margin-bottom:8px;}

/deep/.personMapLabel{
  background: rgba(0,45,105,0.7);
  padding:8px;
  color:#d5f4ff;
  font-size:14px;
  border:1px solid #035877;
}
</style>

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部