下载npm install echarts
在哪里用哪里引入import * as echarts from 'echarts';
根据步骤进行将图表渲染到页面
app.vue
- <template>
-
- <!-- 就传这个图表 -->
- <MyEcharts :options="options" ></MyEcharts>
- <button @click="changeOpt">切换样式</button>
-
- <RouterView />
- </template>
-
-
- <script>
- import MyEcharts from './components/MyEcharts.vue'
- import {options1,options2} from './options'
- import _ from 'lodash';
-
- export default {
- name: 'App',
- components: {
- MyEcharts
- },
- data(){
- return {
- //创建一个options.js文件
- options:options1,
-
- //宽度
- width:"600px"
-
-
- }
- },
- methods: {
- changeOpt() {
- if (_.isEqual(this.options, options1)) {
- this.options = options2; // 切换到options2
- console.log('Switched to options2');
- } else {
- this.options = options1; // 切换回options1
- console.log('Switched to options1');
- }
- }
- }
- }
-
- </script>
-
-
- <style scoped>
-
- </style>
options.js
-
-
- export const options1 = {
- color:['rad'],
- title: {
- text: "ECharts 入门示例",
- },
- tooltip: {},
- legend: {
- data: ["销量"],
- },
- xAxis: {
- data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
- },
- yAxis: {},
- series: [
- {
- name: "销量",
- type: "bar",
- data: [5, 20, 36, 10, 10, 20],
- },
- ]
-
-
- }
-
-
- export const options2 = {
-
- color:['tomato'],
-
- title: {
- text: "ECharts 入门示例1",
- },
- tooltip: {},
- legend: {
- data: ["销量"],
- },
- xAxis: {
- data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
- },
- yAxis: {},
- series: [
- {
- name: "销量",
- type: "bar",
- data: [50, 100, 36, 100, 200, 250],
- },
- ]
-
-
- }
-
MyEcharts.vue
- <template>
-
-
- <div :id="uuid" :style="style" >div>
- template>
- <script>
- import * as echarts from "echarts";
-
- //准备一个生成uuid的方法
- const idGen=()=>{
- return new Date().getTime()
- }
-
- export default {
-
- props:{
- height:{
- type:String,
- default:"400px"
-
- },
- width:{
- type:String,
- default:"600px"
- },
- options:{
- type:Object,
- default:null
- }
-
- },
-
-
- data() {
- return {
- //现将id改为自动生成的
- uuid: null,
- myChart:null
- };
- },
-
- //实现响应式
- watch:{
-
- options(){
- if(this.myChart){
- this.myChart.setOption(this.options)
- }
-
- }
-
-
- },
- computed:{
- style(){
- return {
- height:this.height,
- width:this.width
- }
- }
-
- },
- created(){
- this.uuid = idGen();
- },
-
- //一进入页面就开始渲染Echarts图表
- mounted() {
- //官方流程
- // 基于准备好的dom,初始化echarts实例
- //准备实例
- this.myChart = echarts.init(document.getElementById(this.uuid));
-
- // 指定图表的配置项和数据
- //组织配置项
-
- // 使用刚指定的配置项和数据显示图表。
- //应用配置项
- this.myChart.setOption(this.options);
- },
- };
- script>