项目说明
【配置环境】
- vue-cli^4.5.0,创建项目过程请参考 https://cli.vuejs.org/zh/
- vue^3.0.0, https://v3.cn.vuejs.org/
- echarts^5.1.2,https://echarts.apache.org/zh/index.html
注:本文只针对测试过的版本进行讲解,其他版本如有问题,可以留言或修改配置进行测试;
一、配置步骤
1. 安装echarts
通过 npm 获取 echarts
npm install echarts --save
2. 按需引入echarts
按需引入可参考官网示例中给出的例子,在完整代码里,选择按需引入,即可看到对应代码:
接下来,打开 main.js 文件,写入代码:
注意:按需引入后,全局使用 echarts 需要先写入全局属性,这里与 vue2.x 有区别,官方文档有示例:
// 之前(Vue 2.x)
Vue.prototype.$http = () => {}
// 之后(Vue 3.x)
const app = createApp({})
app.config.globalProperties.$http = () => {}
此时,我们注入 echarts 到全局:
app.config.globalProperties.$echarts = echarts;
3.实现地图展示
- views 文件夹下建立 Emap.vue 文件
- assets/json 下放入已下载好的 china.json 文件,本项目 json 地址 https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json
中国地图 json 文件获取地址:http://datav.aliyun.com/tools/atlas/index.html
本项目用 vue3 的 setup 形式编写项目,值得注意的是 setup 函数内是无法使用 this 的,我们利用官方文档给出的 getCurrentInstance 来获取实例:
import { getCurrentInstance} from 'vue';
在 setup 中获取我们之前注入全局的echarts:
const internalInstance = getCurrentInstance();
const { $echarts } = internalInstance.appContext.config.globalProperties;
注:echarts 在初始化前要设置好样式!
echarts的配置和注册代码要写入 setup 的 onMounted,确保 dom 已挂载完毕再进行其他操作,onMounted 也是要先引入的:
import { getCurrentInstance, onMounted } from 'vue';
其他代码基本和以前echarts配置操作一致,这里不在赘述,直接上本页全部代码:
<template>
<div id="Emap"></div>
</template>
<script>
import { getCurrentInstance, onMounted } from 'vue';
// 引入中国地图json文件
import chinaMap from '../assets/json/china.json';
export default {
name: 'Emap',
setup() {
const internalInstance = getCurrentInstance();
const { $echarts } = internalInstance.appContext.config.globalProperties;
onMounted(() => {
const myChart = $echarts.init(document.getElementById('Emap'));
const option = {
tooltip: {
trigger: 'item',
},
visualMap: [
{
type: 'continuous',
min: 0,
max: 1000,
text: ['High', 'Low'],
realtime: false,
calculable: true,
inRange: {
color: ['lightskyblue', 'yellow', 'orangered'],
},
},
],
series: {
type: 'map',
map: 'china',
data: [
{
name: '北京市',
value: 800,
},
{
name: '云南省',
value: 400,
},
],
},
};
$echarts.registerMap('china', chinaMap);
myChart.setOption(option);
});
},
};
</script>
<style scoped>
#Emap {
border: 1px solid #ccc;
width: 500px;
height: 500px;
}
</style>
总结
完整代码,请到项目 demo 地址:https://gitee.com/feiyunan/blog-demo/tree/master/demo_01