znlgis 博客

GIS开发与技术分享

Vue3 大屏可视化平台开发指南

一、自定义开发

1. 添加新图表

步骤一:创建图表组件

src/components/charts/ 目录下创建新组件:

<!-- src/components/charts/MyChart.vue -->
<template>
  <div ref="chartRef" class="my-chart"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { getCommonChartOption } from '@/utils'

const chartRef = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  
  const option = {
    ...getCommonChartOption(),
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar'
    }]
  }
  
  chartInstance.setOption(option)
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', chartInstance.resize)
})

onUnmounted(() => {
  window.removeEventListener('resize', chartInstance.resize)
  chartInstance?.dispose()
})
</script>

<style scoped>
.my-chart {
  width: 100%;
  height: 300px;
}
</style>

步骤二:在页面中使用

<script setup>
import MyChart from '@/components/charts/MyChart.vue'
</script>

<template>
  <ChartCard title="我的图表">
    <MyChart />
  </ChartCard>
</template>

2. 修改主题样式

修改主题配色

编辑 src/config/theme.config.js

export const THEME_CONFIG = {
  primaryColor: '#2C58A6',      // 主色调
  backgroundColor: '#001d58',    // 背景色
  cardBgColor: '#034c6a',       // 卡片背景色
  borderColor: '#2C58A6',       // 边框颜色
  textColor: '#ffffff',         // 文字颜色
  chartColors: [                // 图表颜色系列
    '#5490CB', '#63B2EE', '#76DA91', 
    '#F8CB7F', '#F89588', '#7CD6CF',
    '#9192AB', '#7898E1', '#EFA666'
  ]
}

修改全局样式

编辑 src/assets/styles/global.scss

// 自定义变量
$primary-color: #2C58A6;
$background-color: #001d58;

// 全局样式
body {
  background-color: $background-color;
  color: #ffffff;
}

// 卡片样式
.card {
  background-color: rgba(3, 76, 106, 0.8);
  border: 1px solid $primary-color;
  border-radius: 4px;
}

3. 添加新功能模块

创建 Composable

// src/composables/useMyFeature.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useMyFeature() {
  const data = ref([])
  const loading = ref(false)
  const error = ref(null)
  
  let timer = null
  
  const fetchData = async () => {
    loading.value = true
    try {
      // 获取数据逻辑
      const response = await fetch('/api/data')
      data.value = await response.json()
    } catch (e) {
      error.value = e
    } finally {
      loading.value = false
    }
  }
  
  const startAutoUpdate = (interval = 5000) => {
    timer = setInterval(fetchData, interval)
  }
  
  const stopAutoUpdate = () => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }
  
  onMounted(() => {
    fetchData()
    startAutoUpdate()
  })
  
  onUnmounted(() => {
    stopAutoUpdate()
  })
  
  return {
    data,
    loading,
    error,
    fetchData,
    startAutoUpdate,
    stopAutoUpdate
  }
}

在组件中使用

<script setup>
import { useMyFeature } from '@/composables/useMyFeature'

const { data, loading, error, fetchData } = useMyFeature()
</script>

<template>
  <div v-if="loading">加载中...</div>
  <div v-else-if="error"></div>
  <div v-else>
    <!-- 显示数据 -->
  </div>
</template>

二、接入真实数据

1. 创建 API 服务

// src/api/index.js
import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(config => {
  // 添加 token 等
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

export default api

// 具体接口
export const getStatistics = () => api.get('/statistics')
export const getPersonnelList = () => api.get('/personnel')
export const getChartData = (type) => api.get(`/chart/${type}`)

2. 替换模拟数据

修改 src/views/Dashboard.vue

<script setup>
import { ref, onMounted } from 'vue'
import { getStatistics, getChartData } from '@/api'

const statistics = ref([])
const chartData = ref({})

onMounted(async () => {
  // 替换 mock 数据为真实 API 调用
  statistics.value = await getStatistics()
  chartData.value = await getChartData('monthly')
})
</script>

3. 配置环境变量

创建 .env.local 文件:

VITE_API_BASE_URL=http://your-api-server.com/api

三、扩展地图功能

1. 添加自定义图层

// 添加标注图层
const addMarkerLayer = (map, markers) => {
  markers.forEach(marker => {
    const markerObj = new T.Marker(
      new T.LngLat(marker.lng, marker.lat),
      {
        icon: new T.Icon({
          iconUrl: marker.iconUrl,
          iconSize: new T.Point(24, 24)
        })
      }
    )
    
    // 添加点击事件
    markerObj.addEventListener('click', () => {
      handleMarkerClick(marker)
    })
    
    map.addOverLay(markerObj)
  })
}

2. 添加信息窗口

const showInfoWindow = (map, position, content) => {
  const infoWindow = new T.InfoWindow(content, {
    closeButton: true,
    autoPan: true
  })
  
  map.openInfoWindow(
    infoWindow, 
    new T.LngLat(position.lng, position.lat)
  )
}

3. 添加绘制功能

// 绘制多边形
const drawPolygon = (map, points) => {
  const polygon = new T.Polygon(
    points.map(p => new T.LngLat(p.lng, p.lat)),
    {
      color: '#2C58A6',
      weight: 2,
      opacity: 0.8,
      fillColor: '#2C58A6',
      fillOpacity: 0.3
    }
  )
  
  map.addOverLay(polygon)
  return polygon
}

四、测试与调试

1. 性能调试

// 使用性能监控
import { usePerformanceMonitor } from '@/composables/usePerformanceMonitor'

const { fps, memoryUsage, performanceWarnings, getPerformanceReport } = usePerformanceMonitor()

// 打印性能报告
console.log(getPerformanceReport())

2. 日志调试

import { logDebug, logInfo, PerformanceTimer } from '@/utils/logger'

// 详细日志(仅开发环境)
logDebug('详细调试信息', someData)

// 性能计时
const timer = new PerformanceTimer('数据处理')
// ... 处理逻辑
timer.end() // 输出耗时

3. 关闭生产环境日志

src/config/dashboard.config.js 中配置:

logging: {
  enableConsoleLog: import.meta.env.DEV,  // 仅开发环境启用
  logLevel: import.meta.env.DEV ? 'debug' : 'error'
}

五、最佳实践

1. 组件设计原则

2. 性能优化建议

3. 代码规范

六、学习资源