构建项目
vue使用typescript 最好是利用 vue-cli3,使用教程网上较多。不过多赘述,一下是使用步骤:
- 下载vue-cli3
npm/cnpm install -g @vue/cli; - 创建vue项目
vue create [myProject]
提示:你可以选择默认选项,使用脚手架默认的插件和依赖,也可以手动选择; - 启动项目
npm run serve
使用echarts
- 下载依赖
npm/cnpm install echarts @types/echarts --save;
同时下载echarts 和 typescript 版的 echarts(@types/echarts)
复制代码
- 在项目根目录创建一个shims-echart.d.ts文件,贴入如下代码:
import Vue from 'vue';
declare module 'vue/types/vue' {
interface Vue {
$echarts: any
}
}
复制代码
- 在main.ts文件中引入echarts,并设置为vue的属性
...
import Echart from 'echarts';
Vue.prototype.$echarts = Echart;
...
复制代码
- 在组件中使用echarts
在组件类中定义一个公共变量$charts,类型跟shims-echart.d.ts中的一样
代码如下(option的代码省略,太长了,你们也不喜欢看,自己去官网找找):
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>
<div id="myEcharts" style="height: 400px;"></div>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
@Component({
components: {
HelloWorld,
},
})
export default class Home extends Vue {
public $echarts: any;
private options: object = {
...
};
private mounted() {
const ele = document.getElementById('myEcharts');
const chart: any = this.$echarts.init(ele);
chart.setOption(this.options);
}
}
</script>
复制代码
效果图:
这是我自己捣鼓出来的一种用法,缺陷什么的还没考虑。如有问题,欢迎指正。如果大家喜欢,跪求一个赞;
所有评论(0)