vue+超图+openlayer

1.实现地图图层服务展示及切换

2.时间线切换

3.地图下钻到镇到村,并返回当前区域编码

代码如下:

<template>
  <div style="width: 100%; height: 100%">
    <div id="plantMap2"></div>
    <div class="reBackIcon" @click="reback" v-show="reBackIcon" :class="{reBackIcon1:sidePage==false}"></div>
    <!--时间轴-->
    <div class="timeLine" v-if="currentIndex==0">
      <TimeLine :dataSource="dataSource" @dataHandle="getNewTime"></TimeLine>
    </div>
    <div class="timeLine" v-if="currentIndex==1">
      <TimeLine :dataSource="dataSource1" @dataHandle="getNewTime1"></TimeLine>
    </div>
    <div class="timeLine" v-if="currentIndex==2">
      <TimeLine :dataSource="dataSource2" @dataHandle="getNewTime2"></TimeLine>
    </div>
    <!--    底部切换按钮-->
    <div class="yearBox">
      <div class="moreYear" v-for="(item, index) in tabList" :key="index" :class="currentIndex == index ? 'moreYearActive' : ''" @click="changeType(index)">
        <a href="javascript:void(0)"> {{ item }} </a>
      </div>
    </div>
    <div class="moreYearBox" v-show="showMoreTab" :class="{moreYearBox1:sidePage==false}">
      <el-checkbox-group v-model="checkList" class="checkBox">
        <el-checkbox v-for="(item, index) in legendList" @change="changeTabitem(item.label)" :key="index" :label="item.label">
          <div style="display: flex; justify-content: center; align-items: center">
            <div class="bacBox" :style="{ backgroundColor: item.color }"></div>
            {{ item.label }}
          </div>
        </el-checkbox>
      </el-checkbox-group>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import TimeLine from './TimeLine'
  export default {
    name: 'centerMap2',
    props: ['sidePage'],
    components: {TimeLine},
    data() {
      return {
        token: 'a2c35af02c6dbee66c1afbcba89cabf8',
        currentIndex: 0,
        tabList: ['冷冻', '干旱', '洪涝'],
        legendList: [
          {
            label: '无冻害',
            color: '#33f2fe'
          },{
            label: '轻度冻害',
            color: '#fffe31'
          },{
            label: '中度冻害',
            color: '#fda726'
          },{
            label: '重度冻害',
            color: '#de041b'
          },
        ], //图例颜色
        checkList: ['无冻害', '轻度冻害', '中度冻害','重度冻害'], //选中的图例
        showMoreTab: true, //右侧图例显隐
        map: null,
        layerList: [], //图层服务存放
        resultData: {}, //弹窗数据内容
        zoom: null, //缩放级别控制
        isMask: 1, //遮罩判断 1--不删除遮罩  0---删除遮罩
        reBackIcon: false, //右上角返回按钮显隐
        observer: null, //监听可视变量
        region:'',
        village:'',
        zhenFeatures:{},
        zhenCoordinates:[],
        rebackName:'黄岛区',
        dataSource:[{name:'2022-12-20'},{name:'2023-01-03'}],
        dataSource1:[
                {name:'2022-12-20'},
                // {name:'2023-01-03'},
                // {name:'2023-02-20'},
                // {name:'2023-03-08'},
                {name:'2023-05-19'},
          ],
        dataSource2:[{name:'2020-05-26'},{name:'2022-06-25'}],
        oldTime:'2022-12-20',
        oldTime1:'2022-12-20',
        oldTime2:'2020-05-26',
      }
    },
    mounted() {
      this.initMap()
      this.showDaChangArea()
      this.$emit('showLeft')
    },
    methods: {
      getNewTime(value){
        this.oldTime=value.name
        this.getLayerData()
        //this.hiddenLayers(this.checkList)
        this.addLayers(this.checkList,this.layerList)
      },
      getNewTime1(value){
        this.oldTime1=value.name
        this.getLayerData()
        //this.hiddenLayers(this.checkList)
        this.addLayers(this.checkList,this.layerList1)
      },
      getNewTime2(value){
        this.oldTime2=value.name
        this.getLayerData()
        //this.hiddenLayers(this.checkList)
        this.addLayers(this.checkList,this.layerList2)
      },
      //下方按钮切换
      changeType(index) {
        this.currentIndex = index
        this.hiddenLayers(this.checkList)
        if (this.currentIndex == 0) {
          this.checkList =  ['无冻害', '轻度冻害', '中度冻害','重度冻害']
          this.legendList =[
            {
              label: '无冻害',
              color: '#33f2fe'
            },{
              label: '轻度冻害',
              color: '#fffe31'
            },{
              label: '中度冻害',
              color: '#fda726'
            },{
              label: '重度冻害',
              color: '#de041b'
            },
          ]
          this.addLayers(this.checkList,this.layerList)
        }
        else if(this.currentIndex == 1) {
          this.checkList = [ '湿润', '适宜', '轻度干旱' ,'中度干旱','重度干旱']
          this.legendList = [
            {
              label: '湿润',
              color: '#1685fc'
            },{
              label: '适宜',
              color: '#33f2fe'
            },{
              label: '轻度干旱',
              color: '#fffe31'
            },{
              label: '中度干旱',
              color: '#fda726'
            },{
              label: '重度干旱',
              color: '#de041b'
            },
          ]
          this.addLayers(this.checkList,this.layerList1)
        }else if(this.currentIndex == 2) {
          this.checkList = ['洪涝']
          this.legendList = [
            {
              label: '洪涝',
              color: '#20bcdc'
            }
          ]
          this.addLayers(this.checkList,this.layerList2)
        }
        this.reback()
        this.showMoreTab = true
      },
      //图例切换
      changeTabitem(type) {
        if(this.currentIndex == 0){
          if (this.checkList.indexOf(type) != -1) {
            this.addLayers(this.checkList,this.layerList,type)
          } else {
            this.hiddenLayers(this.checkList, type)
          }
        }else if(this.currentIndex == 1){
          if (this.checkList.indexOf(type) != -1) {
            this.addLayers(this.checkList,this.layerList1,type)
          } else {
            this.hiddenLayers(this.checkList, type)
          }
        }else {
          if (this.checkList.indexOf(type) != -1) {
            this.addLayers(this.checkList,this.layerList2,type)
          } else {
            this.hiddenLayers(this.checkList, type)
          }
        }
      },
      //左上角返回按钮
      reback() {
        if(this.rebackName == '黄岛区'){
          this.isMask = 0
          this.cancelMask()
          var view = this.map.getView()
          view.animate({
            center: [119.873281, 35.859051],
            zoom: 11,
            duration: 500
          })
          this.$emit('obtainName', '','')
          this.reBackIcon = false
          this.map.getAllLayers().forEach((lyr) => {
            if (lyr.get('id')) {
              if (lyr.get('id') == 'cjqy') {
                this.map.removeLayer(lyr)
              }
            }
          })
        }else{
          this.$emit('obtainName', this.region,'')
          this.rebackZhen()
        }
      },
      //返回到镇
      rebackZhen(){
        this.rebackName = '黄岛区'
        var view = this.map.getView()
        view.animate({
          center:this.center,
          zoom:this.zoom,
          duration: 500
        })
        var layergaoliang2 = this.map
                .getLayers()
                .getArray()
                .find((layer) => layer.get('id') === 'dianjigaoliang2')
        this.map.removeLayer(layergaoliang2)
        var layerzhezhao = this.map
                .getLayers()
                .getArray()
                .find((layer) => layer.get('id') === 'zhezhao')
        this.map.removeLayer(layerzhezhao)
        this.addConver( this.zhenCoordinates, 'rgba(0,28,58,0.7)', 'zhezhao')
        var llll = new ol.format.GeoJSON().readFeatures(this.zhenFeatures)
        var selectFeatureSource = new ol.source.Vector()
        selectFeatureSource.addFeatures(llll)
        const style = new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'rgba(94, 255, 255, 1.0)',
            // lineDash: [10, 10],
            width: 3.5
          })
        })
        var vectorQuery = new ol.layer.Vector({
          id: 'dianjigaoliang',
          source: selectFeatureSource
        })
        vectorQuery.setStyle(style)
        this.map.addLayer(vectorQuery)
      },
      //初始化地图
      async initMap() {
        this.getLayerData()
        this.map = new ol.Map({
          target: 'plantMap2',
          controls: ol.control.defaults({
            attributionOptions: {
              collapsed: true
            },
            zoom: false,
            rotate: false,
            attribution: false
          }),
          view: new ol.View({
            center: [119.873281, 35.859051],
            zoom: 11,
            projection: 'EPSG:4326'
          }),
          layers: [
            new ol.layer.Tile({
              source: new ol.source.Tianditu({
                layerType: 'img',
                key: '1d109683f4d84198e37a38c442d68311'
              })
            }),
            new ol.layer.Tile({
              source: new ol.source.Tianditu({
                layerType: 'img',
                //isLabel: true,
                key: '1d109683f4d84198e37a38c442d68311'
              })
            })
          ]
        })
        var layer = new ol.layer.Tile({
          source: new ol.source.TileSuperMapRest({
            url: 'http://0.0.0.0:8090/iserver/services/map-huangdaoqu_bianjie/rest/maps/XJQY3702112019WGS84%40huangdaoqu_bianjie',
            cacheEnabled: false
          }),
          projection: 'EPSG:4326', //3857
          zIndex:9999
        })
        this.map.addLayer(layer)
        this.addLayers(this.checkList,this.layerList)
        this.map.on('contextmenu', this.cancelMask)
        this.map.on('singleclick', this.addClickEvent)
        // this.donghua()
      },
      //添加图层
      addLayers(checkList,mapLayerArr, type) {
        var geoserverUrl='http://0.0.0.0:8090/iserver/services'
        //根据type判断是否是单个点击图例
        if (type == undefined) {
          mapLayerArr.forEach((item) => {
            checkList.forEach((label) => {
              if (label == item.type) {
                //添加rest图层
                var layer = new ol.layer.Tile({
                  source: new ol.source.TileSuperMapRest({
                    url: geoserverUrl + `/map-${item.setOf}/rest/maps/${item.name}@${item.setOf}`,
                    cacheEnabled: false
                  }),
                  projection: 'EPSG:4326',
                  opacity: 1
                })
                layer.type = item.type
                this.map.addLayer(layer)
              }
            })
          })
        } else {
          mapLayerArr.forEach((item) => {
            if (type == item.type) {
              var layer = new ol.layer.Tile({
                source: new ol.source.TileSuperMapRest({
                  url: geoserverUrl + `/map-${item.setOf}/rest/maps/${item.name}@${item.setOf}`,
                  cacheEnabled: false
                }),
                projection: 'EPSG:4326',
                opacity: 1
              })
              layer.type = type
              this.map.addLayer(layer)
            }
          })
        }
      },
      //隐藏图层
      hiddenLayers(checkList, type) {
        //判断是否单个隐藏
        if (type == undefined) {
          checkList.forEach((item) => {
            this.map.getAllLayers().forEach((lyr) => {
              if (lyr?.type) {
                if (item == lyr.type) {
                  this.map.removeLayer(lyr)
                }
              }
            })
          })
        } else {
          this.map.getAllLayers().forEach((lyr) => {
            if (type == lyr.type) {
              this.map.removeLayer(lyr)
            }
          })
        }
      },
      //获取图层数据
      getLayerData() {
        var oldTime=this.oldTime
        var str=oldTime.replace(/-/g,'_')
        var oldTime1=this.oldTime1
        var str1=oldTime1.replace(/-/g,'_')
        var oldTime2=this.oldTime2
        var str2=oldTime2.replace(/-/g,'_')
        this.layerList = [
          {
            setOf: `${oldTime}-lengdong`,
            name: `T${str}_wudonghai`,
            type:'无冻害',
            url:''
          },
          {
            setOf: `${oldTime}-lengdong`,
            name: `T${str}_qingdudonghai`,
            type:'轻度冻害'
          },
          {
            setOf: `${oldTime}-lengdong`,
            name: `T${str}_medium_donghai`,
            type:'中度冻害'
          },
          {
            setOf: `${oldTime}-lengdong`,
            name: `T${str}_serious_donghai`,
            type:'重度冻害'
          }
        ]
        this.layerList1 = [
          {
            setOf: `${oldTime1}-ganhan`,
            name: `T${str1}_shirun`,
            type:'湿润'
          },
          {
            setOf: `${oldTime1}-ganhan`,
            name: `T${str1}_shiyi`,
            type:'适宜'
          },
          {
            setOf: `${oldTime1}-ganhan`,
            name: `T${str1}_qingduganhan`,
            type:'轻度干旱'
          },
          {
            setOf: `${oldTime1}-ganhan`,
            name: `T${str1}_medium_ganhan`,
            type:'中度干旱'
          },
          {
            setOf: `${oldTime1}-ganhan`,
            name: `T${str1}_serious_ganhan`,
            type:'重度干旱'
          }
        ]
        this.layerList2 = [
          {
            setOf: `${oldTime2}-honglao`,
            name: `T${str2}_honglao`,
            type:'洪涝'
          }
        ]
      },
      //点击事件
      addClickEvent(e) {
        this.cancelMask()
        this.zoom = this.map.getView().getZoom()
        var coodinate = e.coordinate
        var lon = coodinate[0]
        var lat = coodinate[1]
        var view = this.map.getView()
        axios.get('/js/huangdao.json').then(({ data }) => {
          var geojson = new ol.format.GeoJSON().readFeatures(data)
          var selectFeatureSource = new ol.source.Vector()
          selectFeatureSource.addFeatures(geojson)
          var vectorQuery = new ol.layer.Vector({
            source: selectFeatureSource
          })
          var features = vectorQuery.getSource().getFeatures()
          for (var i = 0; i < features.length; i++) {
            var polygon = features[i].getGeometry()
            if (polygon.intersectsCoordinate(coodinate)) {
              if (this.zoom <= 11) {
                var url= 'http://0.0.0.0:8090/iserver/services/map-huangdaoqu_bianjie/rest/maps/XJQY3702112019WGS84%40huangdaoqu_bianjie'
                var query= 'XJQY3702112019WGS84@huangdaoqu_bianjie'
                this.getDrilling(e,query,url,12)
                var layer = new ol.layer.Tile({
                  source: new ol.source.TileSuperMapRest({
                    url: 'http://0.0.0.0:8090/iserver/services/map-huangdaoqu_bianjie/rest/maps/CJQY3702112019WGS84%40huangdaoqu_bianjie',
                    //rasterfunction: new SuperMap.NDVIParameter({ redIndex: 0, nirIndex: 2 }),
                    cacheEnabled: false
                  }),
                  id: 'cjqy',
                  projection: 'EPSG:4326' //3857
                })
                this.map.addLayer(layer)
              } else{
                var url =
                        'http://0.0.0.0:8090/iserver/services/map-huangdaoqu_bianjie/rest/maps/CJQY3702112019WGS84%40huangdaoqu_bianjie'
                var query = 'CJQY3702112019WGS84@huangdaoqu_bianjie'
                this.getDrilling1(e, query, url, 14)
              }
            }
          }
        })
      },
      //下钻到镇
      getDrilling(e, query, url,zoom){
        this.reBackIcon = true
        this.rebackName='黄岛区'
        var dianjigaoliang2 = this.map
                .getLayers()
                .getArray()
                .find((layer) => layer.get('id') === 'dianjigaoliang2')
        this.map.removeLayer(dianjigaoliang2)
        var zhezhao = this.map
                .getLayers()
                .getArray()
                .find((layer) => layer.get('id') === 'zhezhao')
        this.map.removeLayer(zhezhao)
        var point = new ol.geom.Point(e.coordinate)
        var param = new ol.supermap.QueryByGeometryParameters({
          queryParams: {
            name: query
          },
          geometry: point
        })
        new ol.supermap.QueryService(url).queryByGeometry(param, (data) => {
          //如果有数据
          if (data.result.currentCount != 0) {
            var coodinate = e.coordinate
            var lon = coodinate[0]
            var lat = coodinate[1]
            var view = this.map.getView()
            view.animate({
              center: [lon, lat],
              zoom,
              duration: 500
            })
            this.center=[lon, lat]
            this.zoom=zoom
            this.isMask = 0
            this.resultData = data?.result?.recordsets[0]?.features?.features[0]?.properties
            this.region = this.resultData.XJQYDM
            this.village = ''
            this.$emit('obtainName', this.region,this.village)
            this.zhenCoordinates =
                    data?.result?.recordsets[0]?.features?.features[0]?.geometry?.coordinates
            this.addConver( this.zhenCoordinates, 'rgba(0,28,58,0.7)', 'zhezhao')
            this.zhenFeatures=data.result.recordsets[0].features
            var llll = new ol.format.GeoJSON().readFeatures(this.zhenFeatures)
            var selectFeatureSource = new ol.source.Vector()
            selectFeatureSource.addFeatures(llll)
            const style = new ol.style.Style({
              stroke: new ol.style.Stroke({
                color: 'rgba(94, 255, 255, 1.0)',
                // lineDash: [10, 10],
                width: 3.5
              })
            })
            var vectorQuery = new ol.layer.Vector({
              id: 'dianjigaoliang',
              source: selectFeatureSource
            })
            vectorQuery.setStyle(style)
            this.map.addLayer(vectorQuery)
          } else {
            this.isMask = 1
          }
        })
        this.isMask = 0
        this.cancelMask()
        var view = this.map.getView()
        view.animate({
          center: [119.873281, 35.859051],
          zoom: 11,
          duration: 500
        })

      },
      //下钻到村
      getDrilling1(e, query, url, zoom) {
        this.reBackIcon = true
        this.rebackName='镇'
        var layergaoliang = this.map
                .getLayers()
                .getArray()
                .find((layer) => layer.get('id') === 'dianjigaoliang')
        this.map.removeLayer(layergaoliang)
        var zhezhao = this.map
                .getLayers()
                .getArray()
                .find((layer) => layer.get('id') === 'zhezhao')
        this.map.removeLayer(zhezhao)
        var point = new ol.geom.Point(e.coordinate)
        var param = new ol.supermap.QueryByGeometryParameters({
          queryParams: {
            name: query
          },
          geometry: point
        })
        new ol.supermap.QueryService(url).queryByGeometry(param, (data) => {
          //如果有数据
          if (data.result.currentCount != 0) {
            var coodinate = e.coordinate
            var lon = coodinate[0]
            var lat = coodinate[1]
            var view = this.map.getView()
            view.animate({
              center: [lon, lat],
              zoom,
              duration: 500
            })
            this.isMask = 0
            this.resultData = data?.result?.recordsets[0]?.features?.features[0]?.properties
            this.village = this.resultData.CJQYDM
            this.$emit('obtainName', this.region,this.village)
            var coordinates =
                    data?.result?.recordsets[0]?.features?.features[0]?.geometry?.coordinates
            this.addConver(coordinates, 'rgba(0,28,58,0.7)', 'zhezhao')
            var llll = new ol.format.GeoJSON().readFeatures(data.result.recordsets[0].features)
            var selectFeatureSource = new ol.source.Vector()
            selectFeatureSource.addFeatures(llll)
            const style = new ol.style.Style({
              fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255,0.3)'
              }),
              stroke: new ol.style.Stroke({
                color: 'rgba(94, 255, 255, 1.0)',
                width: 4
              })
            })
            var vectorQuery = new ol.layer.Vector({
              id: 'dianjigaoliang2',
              source: selectFeatureSource
            })
            vectorQuery.setStyle(style)
            this.map.addLayer(vectorQuery)

          } else {
            this.isMask = 1
          }
        })
      },
      //显示黄岛区域
      showDaChangArea() {
        axios.get('/js/huangdao.json').then(({ data }) => {
          const fts = new ol.format.GeoJSON().readFeatures(data)
          const ft = fts[0]
          this.addConver(ft.getGeometry().getCoordinates(), 'rgba( 11, 14, 62, 0.85)', 'huangdao')
        })
      },
      //添加遮罩
      addConver(data, color, id) {
        let source = new ol.source.Vector()
        var converLayer = new ol.layer.Vector({
          id: id,
          source: source,
          style: new ol.style.Style({
            fill: new ol.style.Fill({
              color: color
            })
          })
        })
        const converGeom = this.erase(data)
        const convertFt = new ol.Feature({
          geometry: converGeom
        })
        converLayer.getSource().addFeature(convertFt)
        this.map?.addLayer(converLayer)
      },
      //擦除操作,生产遮罩范围
      erase(data) {
        const extent = [-180, -90, 180, 90]
        const polygonRing = ol.geom.Polygon.fromExtent(extent)
        const coords = data
        if (coords) {
          coords.forEach((coord) => {
            const linearRing = new ol.geom.LinearRing(coord[0])
            polygonRing.appendLinearRing(linearRing)
          })
          return polygonRing
        } else {
          return
        }
      },
      //取消遮罩和点击高亮
      cancelMask(e) {
        if (this.isMask == 0) {
          var layerzhezhao = this.map
                  .getLayers()
                  .getArray()
                  .find((layer) => layer.get('id') === 'zhezhao')
          this.map.removeLayer(layerzhezhao)
          var layergaoliang = this.map
                  .getLayers()
                  .getArray()
                  .find((layer) => layer.get('id') === 'dianjigaoliang')
          var layergaoliang2 = this.map
                  .getLayers()
                  .getArray()
                  .find((layer) => layer.get('id') === 'dianjigaoliang2')
          this.map.removeLayer(layergaoliang)
          this.map.removeLayer(layergaoliang2)
        }
      },
      donghua() {
        var view = this.map.getView()
        view.animate({
          center: [119.773281, 35.859051],
          zoom: 11,
          duration: 3000
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .timeLine{
    width: 24vw;
    height: 10vh;
    position: absolute;
    bottom: 10vh;
    left: 34.5vw;
    opacity: 1;
      background: url("../../img/planting/main2/timeline-bg.png");
      background-size: 100% 100%;

  }
  a {
    color: inherit;
    text-decoration: none;
  }

  a:hover {
    color: inherit;
    text-decoration: none;
  }

  a:visited {
    color: inherit;
    text-decoration: none;
  }

  a:active {
    color: inherit;
    text-decoration: none;
  }
  .yearBox {
    width: 50%;
    height: 4vh;
    position: absolute;
    bottom: 2vh;
    left: 35.5vw;
    display: flex;
    /* justify-content: center; */
  }
  .moreYear {
    width: 7vw;
    height: 100%;
    background-image: url('../../img/landSource/main3/001.png');
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 0.5vw;
  }
  .moreYearActive {
    background-image: url('../../img/landSource/main3/002.png');
    background-size: 100% 100%;
  }
  #plantMap2 {
    width: 100%;
    height: 100%;
  }
  .moreYearBox1 {
    right: 3vw !important;
  }
  .moreYearBox {
    width: 8vw;
    background-color: rgba(255, 255, 255, 0.07);
    padding-bottom: 0.5vh;
    position: absolute;
    right: 26vw;
    bottom: 4vh;
  }
  .my-close {
    position: absolute;
    top: 1vh;
    right: 1vw;
  }
  .checkBox {
    margin-top: 2vh;
  }
  .bacBox {
    width: 1vh;
    height: 1vh;
    border-radius: 2px;
    margin-right: 0.5vw;
  }
  ::v-deep .el-checkbox-group {
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-right: 3.5vw;
  }
  ::v-deep .el-checkbox {
    margin: 0 auto;
    margin-bottom: 0.5vh;
    width: 50%;
  }


  .s-bottom {
    position: absolute;
    bottom: 1vh;
    left: 45vw;
    display: flex;
    justify-content: center;
    width: 8vw;
    /*height: 10vh;*/
    .bot-item{
      width: 100%;
      height: 100%;
      cursor: pointer;
      img{
        width: 3vw;
        height: 3vw;
      }
      .bot-title{
        color: #5fb4fa;
      }
      .active{
        color: #fff;
      }

    }
  }
</style>

时间线:

<template>
    <div class="timeline">
        <el-slider
            v-model="value2"
            :step="step"
            :marks="marks"
            show-stops
            :show-tooltip="false"
            :min="min"
            :max="max"
        ></el-slider>
        <div class="optionWrapper">
            <img style="width: 0.8vh;height: 1.3vh" @click="leftHandle" src="../../img/planting/main2/left.png" alt="《" />
            <img style="width: 1.7vh;height: 1.7vh;margin-left: 0.5vw" @click="autoPlay" v-if="!times" src="../../img/planting/main2/start.png" alt="||" />
            <img style="width: 1.7vh;height: 1.7vh;margin-left: 0.5vw" @click="pausePlay" v-if="times" src="../../img/planting/main2/stop.png" alt="||" />
            <img style="width: 0.8vh;height: 1.3vh;margin-left: 0.5vw" @click="rightHandle" src="../../img/planting/main2/right.png" alt="》" />
        </div>
    </div>
</template>

<script>
export default {
    props: ['dataSource', 'theme'],
    data() {
        return {
            value2: 0, //当前的值
            marks: {}, //时间轴刻度
            step: 10,
            times: null,
            min: 0,
            max: 100,
        };
    },
    watch: {
        // 监听数值变化进行操作
        value2: function (val, oldVal) {
            // 筛选出原始数据
            const oldData = this.dataSource.find(item => item.name === this.marks[val].label);
            this.$emit('dataHandle', oldData);
        },
        dataSource: function (val, oldVal) {
            //源数据监听
            this.dataHandleInit();
        },
    },
    mounted() {
        this.dataHandleInit(); //
    },
    methods: {
        dataHandleInit() {
            let dataSource = JSON.parse(JSON.stringify(this.dataSource));
            const markNum = dataSource.map(item => item.name);
            this.max = (markNum.length - 1) * 10; //时间轴最大值
            const splitNumber = 10;
            let num = 0;
            let marks = {};
            // 排序,确定marks
            dataSource
                .sort((a, b) => Number(a.name) - Number(b.name))
                .forEach((item, index) => {
                    if (dataSource.length < 10) {
                        marks[num] = { label: item.name };
                    } else {
                        marks[num] = {
                            label: item.name,
                            style: {
                                top: index % 2 === 1 ? '-40px' : '0px',
                            },
                        };
                    }
                    num += splitNumber;
                });
            this.marks = marks; //赋值mark
        },
        // 上一个
        leftHandle() {
            // 判断是不是第一个
            if (this.value2 === 0) {
                this.value2 = this.max;
            } else {
                this.value2 -= this.step;
            }
        },
        // 下一个
        rightHandle() {
            // 判断是否是最后一个
            if (this.value2 === this.max) {
                // 跳转到第一个
                this.value2 = 0;
            } else {
                this.value2 += this.step;
            }
        },
        // 自动播放
        autoPlay() {
            this.times = setInterval(() => {
                this.rightHandle();
            }, 1000 * 2);
        },
        // 暂停播放
        pausePlay() {
            clearInterval(this.times);
            this.times = null;
        },
    },
};
</script>

<style scoped lang="scss">
.timeline {
    width: 100%;
    height: 100%;
    padding: 1vh 1.5vw;
    align-items: center;
    display: flex;

    ::v-deep .el-slider {
        flex: 1;

        .el-slider__runway {
            background-color: rgba(255, 255, 255, 0.2);
            width:12vw;
            margin: auto;
            .el-slider__bar {
                background-color: rgba(108, 177, 184, 1);
                border-radius: 5px;
            }
            // 点
            .el-slider__stop {
                background-color: rgba(108, 177, 184, 1);
                height: 10px;
                width: 1px;
                // top: -2px;
            }

            .el-slider__button {
                display: none;
                // background: linear-gradient(180deg, rgba(101, 220, 252, 1) 0%, rgba(67, 148, 171, 1) 100%);
                // box-shadow: 0px 2px 4px 0px rgba(29, 142, 173, 0.6);
                // filter: blur(0px);
            }

            // marks字
            .el-slider__marks-text {
                width: 4vw;
                text-align: left;
                left: 13%;
                font-size: 14px;
                font-weight: 400;
                color: rgba(255, 255, 255, 1);
            }
        }
    }

    .optionWrapper {
        display: flex;
        align-items: center;
        color: white;
        width: 4vw;
        height: 100%;
        & > img {
            cursor: pointer;
        }
    }
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值