vue-cli4按需引入echarts5实现中国地图


项目说明

【配置环境】

  1. vue-cli^4.5.0,创建项目过程请参考 https://cli.vuejs.org/zh/
  2. vue^3.0.0, https://v3.cn.vuejs.org/
  3. 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.实现地图展示

中国地图 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

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值