温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

chart.js怎么在vue项目中使用

发布时间:2021-04-19 17:55:49 来源:亿速云 阅读:563 作者:Leah 栏目:web开发

今天就跟大家聊聊有关chart.js怎么在vue项目中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

vue是什么软件

Vue是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。

指令

该指令的作用是dom渲染后触发,因为非vue的插件有的是dom必须存在的情况下才可以执行

Vue.directive('loaded-callback', {
 inserted: function (el, binding, vnode) {
  binding.value(el, binding, vnode)
 }
})

安装chartjs

npm install chart.js --save

chartjs 组件

<template>
  <canvas refs="chartcanvas" v-loaded-callback="setCanvas"></canvas>
</template>
<script type="text/javascript">
require('chart.js')
export default{
  name: 'components-base-chartjs',
  props: {
    'data': {},
    'options': {},
    'type': {}
  },
  data:function(){
    return {
      canvas: null,
      chart: null
    }
  },
  watch:{
    canvas: function () { // chart对象生成时触发
      this.initChart()
    },
    data: {
      handler: function () { // 数据变化时触发
        this.updateChart()
      },
      deep: true
    }
  },
  destoryed:function (){
    if(this.cahrt){
      this.cahrt.destroy()
    }
  },
  computed: {
    currentOptions: function (){
      var options = {}
      if(this.options){ // 加载自定义配置参数
        for(var i in this.options){
          options[i] = this.options[i]
        }
      }
      return options
    }
  },
  methods: {
    setCanvas: function(el){ // dom生成时触发
      this.canvas = el
    },
    initChart: function () { // 更新chart结果
      if(this.data && this.currentOptions){ // 保证参数的存在
        this.chart = new Chart(this.canvas.getContext('2d'),{
          type: this.type,
          data: this.data,
          options: this.currentOptions
        })
      }
    },
    updateChart: function () { // 更新chart结果
      this.chart.data = JSON.parse(JSON.stringify(this.data))
      this.chart.update()
    }
  }
}
</script>

用法

<chartjs :options="options" type="pie" :data="data"></chartjs>

看完上述内容,你们对chart.js怎么在vue项目中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI