美文网首页Vue
Vue项目中引用echarts的几种方式

Vue项目中引用echarts的几种方式

作者: 华夏车前子 | 来源:发表于2019-06-05 10:46 被阅读0次

    安装echarts依赖

    npm install echarts -S
    或者使用淘宝的镜像
    npm install -g cnpm --registry=https://registry.npm.taobao.org
    cnpm install echarts -S

    全局引入

    首先在main.js中引入echarts,将其绑定到vue原型上:

    1.  import echarts from 'echarts'
    2. Vue.prototype.$echarts = echarts;
    

    接着,我们就可以在任何一个组件中使用echarts了,接下来我们在初始化项目中的helloWorld组件中使用echarts配置图标,具体如下:

    <template>
        <div>
             <div style="width:500px;height:500px" ref="chart"></div>
        </div>
    </template>
    <script>
    export default{
       data () {
      return {};
     },
     methods: {
      initCharts () {
      let myChart = this.$echarts.init(this.$refs.chart);
      console.log(this.$refs.chart)
      // 绘制图表
      myChart.setOption({
      title: { text: '在Vue中使用echarts' },
      tooltip: {},
      xAxis: {
      data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
      },
      yAxis: {},
      series: [{
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
      }]
      });
      }
       },
       mounted () {
      this.initCharts();
     }
    }
    </script>
    

    这样下来,就可以在项目的任何地方使用echarts了。

    局部使用

    当然,很多时候没必要在全局引入ecahrts,那么我们只在单个组件内使用即可,代码更加简单:

    <template>
    <div>
    <div style="width:500px;height:500px" ref="chart"></div>
    </div>
    </template>
    <script>
    const echarts = require('echarts');
    export default{
    data () {
    return {};
    },
    methods: {
    initCharts () {
    let myChart = echarts.init(this.$refs.chart);
    // 绘制图表
    myChart.setOption({
    title: { text: '在Vue中使用echarts' },
    tooltip: {},
    xAxis: {
    data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
    },
    yAxis: {},
    series: [{
    name: '销量',
    type: 'bar',
    data: [5, 20, 36, 10, 10, 20]
    }]
    });
    }
    },
    mounted () {
    this.initCharts();
    }
    }
    </script>
    

    可以看到,我们直接在组件内引入echarts,接下来跟全局引入的使用一样。区别在于,这种方式如果你想在其他组件内用echarts,则必须重新引入了。

    转载: weixin_39107093

    相关文章

      网友评论

        本文标题:Vue项目中引用echarts的几种方式

        本文链接:https://www.haomeiwen.com/subject/midjxctx.html