使用Vue.js包装器为Chart.js创建漂亮的图表

图表是现代网站和应用程序的重要组成部分。 它们有助于呈现无法轻易用文本表示的信息。 通过以易于阅读和理解的视图显示图表,图表还可以帮助理解通常不会以文本格式显示的数据。

在本文中,我将向您展示如何在Chart.jsVue.js的帮助下以各种图表的形式表示数据。 Chart.js是面向开发人员和设计人员的简单而灵活的JavaScript图表库,该库允许使用HTML5 canvas元素绘制各种图表。 可以在这里阅读有关Chart.js的优秀复习。

Vue.js是一个渐进式JavaScript框架,我们将与Chart.js一起使用以演示图表示例。 如果您是Vue.js的新手,那么可以在SitePoint 上使用Vue.js入门。 我们还将使用Vue CLI来构建我们要构建的演示的Vue.js项目。

女佣定位对象代表不同类型的图表

图表,图表,图表

GitHub上的awesome-vue存储库中有一个很棒的Vue包装器集合,用于各种图表库。 但是,当我们专注于Chart.js时,我们将查看该库的以下包装器:

我们将使用这些包装器来演示如何创建不同类型的图表,并介绍它们各自提供的独特功能。

请注意,本教程的源代码可在GitHub上找到

使用Vue CLI搭建项目

让我们开始使用以下命令安装Vue CLI:

npm install -g @vue/cli

完成后,我们可以通过输入以下内容来开始搭建项目:

vue create chart-js-demo

这将打开一个向导,引导您完成创建新的Vue应用的过程。 回答以下问题:

? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Linter
? Use history mode for router? Yes
? Pick a linter / formatter config: ESLint with error prevention only
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel etc.? In dedicated config files
? Save this as a preset for future projects? No

现在,我们安装Chart.js以及应用程序所需的各种包装器:

cd chart-js-demo
npm install chart.js chartkick hchs-vue-charts vue-chartjs vue-chartkick

提示:如果使用npm 5,则不再需要--save标志,因为所有软件包现在都已自动保存。 在此处阅读有关内容的更多信息。

让我们测试目前为止,然后运行我们的应用程序:

npm run serve

如果一切顺利,则应该可以打开localhost:8080并查看标准的欢迎页面。

基本设定

接下来,我们需要为每个包装器添加一个视图。 在src/views创建以下文件:

  • VueChartJS.vue
  • VueChartKick.vue
  • VueCharts.vue
touch src/views/{VueChartJS.vue,VueChartKick.vue,VueCharts.vue}

然后在src/components创建以下文件:

  • LineChart.vue
  • BarChart.vue
  • BubbleChart.vue
  • Reactive.vue
touch src/components/{LineChart.vue,BarChart.vue,BubbleChart.vue,Reactive.vue}

这些对应于我们将要使用的图表类型。

最后,你可以删除About.vue文件src/views ,该HelloWorld.vue文件src/components ,以及对assets的文件夹src 。 我们将不需要那些。

src目录的内容应如下所示:

.
├── App.vue
├── components
│   ├── BarChart.vue
│   ├── BubbleChart.vue
│   ├── LineChart.vue
│   └── Reactive.vue
├── main.js
├── router.js
└── views
    ├── Home.vue
    ├── VueChartJS.vue
    ├── VueChartKick.vue
    └── VueCharts.vue

添加路线

接下来要做的是创建不同的路线,在其中我们可以查看上面创建的每个包装程序的图表。 我们希望有一个/charts路由来显示使用vue-charts包装器制作vue-charts/chartjs显示以vue-chartjs包装器制作的图表,最后是/chartkick显示由vue-chartkick包装器制作的图表。 我们还将保留/路由以显示“ Home视图。

导航到应用程序的src文件夹,然后打开router.js文件。 用以下内容替换该文件的内容:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home'
import VueChartJS from '@/views/VueChartJS'
import VueChartKick from '@/views/VueChartKick'
import VueCharts from '@/views/VueCharts'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/chartjs',
      name: 'VueChartJS',
      component: VueChartJS
    },
    {
      path: '/chartkick',
      name: 'VueChartKick',
      component: VueChartKick
    },
    {
      path: '/charts',
      name: 'VueCharts',
      component: VueCharts
    }
  ]
})

在这里,我们导入了上面创建的Vue组件。 组件是Vue最强大的功能之一。 它们帮助我们扩展基本的HTML元素以封装可重用的代码。 从高层次上讲,组件是Vue编译器将行为附加到的自定义元素。

最后,我们定义了将服务于显示不同图表所需的不同页面的路线和组件。

添加导航

我们可以在src/App.vue定义要在各个组件之间使用的导航。 我们还将添加一些基本样式:

<template>
  <div id="app">
    <div id="nav">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/chartjs">vue-chartjs</router-link></li>
        <li><router-link to="/charts">vue-charts</router-link></li>
        <li><router-link to="/chartkick">vue-chartkick</router-link></li>
      </ul>
    </div>
    <router-view />
  </div>
</template>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
  height: 90px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
  text-decoration: underline;
}

#nav a.router-link-exact-active {
  color: #42b983;
  text-decoration: none;
}

#nav ul {
  list-style-type: none;
  padding: 0;
}

#nav ul li {
  display: inline-block;
  margin: 0 10px;
}

h1 {
  font-size: 1.75em;
}

h2 {
  line-height: 2.5em;
  font-size: 1.25em;
}
</style>

这里没有什么革命性的。 注意<router-view />组件的使用,这是我们显示视图的地方。

家庭组件

如上所述, Home组件用作默认( / )路由。 打开它,并用下面的代码块替换内容:

<template>
  <section class="hero">
    <div class="hero-body">
      <div class="container">
        <h1>Creating Beautiful Charts Using Vue.js Wrappers For Chart.js</h1>
        <h2>
          Read the article on SitePoint:
          <a href="https://www.sitepoint.com/creating-beautiful-charts-vue-chart-js/">
            
  
  
Creating Beautiful Charts Using Vue.js Wrappers for Chart.js

加布尔玛

在开始添加图表之前,还有一件事。 让我们将Bulma CSS框架添加到应用程序中。 在使用CSS时,这应该使事情变得容易。

打开public/index.html文件,并在head标签内添加以下内容:

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" rel="stylesheet">

现在,如果您访问localhost:8080 ,则应该能够在应用程序的外壳中导航。

最后,我们可以继续创建图表!

用vue-chart.js制作图表

vue-chartjs是一个Chart.js包装器,可让我们轻松创建可重复使用的图表组件。 可重用性意味着我们可以导入基本图表类并将其扩展以创建自定义组件。

话虽如此,我们将演示可以使用vue-chartjs构建的四种类型的图表:折线图,条形图,气泡图和演示反应性的条形图(只要有变化,图表就会更新在数据集中)。

折线图

要创建折线图,我们将创建一个组件以仅呈现这种类型的图表。 打开src/components文件夹内的LineChart.vue组件文件,并添加以下代码:

<script>
  //Importing Line class from the vue-chartjs wrapper
  import { Line } from 'vue-chartjs'

  //Exporting this so it can be used in other components
  export default {
    extends: Line,
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  }
</script>

让我们讨论上面的代码在做什么。 我们要做的第一件事是从vue-chartjs导入所需的图表类(在本例中为Line )并将其导出。

data属性包含一个datacollection对象,该对象包含构建折线图所需的所有信息。 这包括Chart.js配置(如labels ,将在x轴上表示), datasets (将在y轴上表示),以及options对象,该对象控制图表的外观。

mounted函数调用renderChart()来呈现带有作为参数传入的datacollectionoptions对象的图表。

现在,让我们打开views/VueChartJS.vue文件并添加以下代码:

<template>
  <section class="container">
    <h1>Demo examples of vue-chartjs</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <line-chart></line-chart>
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Bubble Chart</h3>
        <!--Bubble Chart example-->
      </div>
      <div class="column">
        <h3>Reactivity - Live update upon change in datasets</h3>
        <!--Reactivity Line Chart example-->
      </div>
    </div>
  </section>
</template>

<script>
  import LineChart from '@/components/LineChart'
  import BarChart from '@/components/BarChart'
  import BubbleChart from '@/components/BubbleChart'
  import Reactive from '@/components/Reactive'

  export default {
    name: 'VueChartJS',
    components: {
      LineChart,
      BarChart,
      BubbleChart,
      Reactive
    }
  }
</script>

VueChartJS.vue文件包含保存HTML代码的template部分,保存JavaScript代码的script部分和保存CSS代码的style部分。

template部分中,我们使用了Bulma中的columns类来创建具有两列和两行的布局。 我们还添加了一个line-chart组件,该组件将在script部分中创建。

script部分中,我们导入了.vue创建的.vue文件,并在components对象中对其进行了引用。 这意味着我们可以在HTML代码中使用它们,如下所示: line-chartbar-chartbubble-chartreactive

现在,如果您导航到/chartjs ,则折线图应显示在该页面上。

请参阅CodePen上的Pen vue-chart.js – SitePoint( @SitePoint折线图

条形图

对于下一个图表,我们将创建一个自定义组件,该组件仅有助于呈现条形图。 打开src/components文件夹内的BarChart.vue组件文件,并添加以下代码:

<script>
  //Importing Bar class from the vue-chartjs wrapper
  import { Bar } from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default {
    extends: Bar,
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  }
</script>

上面的代码与LineChart.vue文件中的代码相似。 唯一的区别是Bar类是导入和扩展的,而不是Line

还有一件事:在看到条形图之前,我们需要编辑VueChartJS.vue文件,并用<bar-chart></bar-chart>替换<!--Bar Chart example--> <bar-chart></bar-chart> 。 我们只是使用在HTML模板内部创建的Bar组件。

见钢笔vuechart-JS -条形图由SitePoint( @SitePoint上) CodePen

气泡图

对于气泡图,我们将创建一个仅有助于渲染气泡图的组件。

注意:气泡图使用气泡/圆圈以三维方法(x,y,r)显示数据。 x用于显示水平轴数据, y用于显示垂直数据, r用于显示各个气泡的大小。

打开src / components文件夹内的BubbleChart.vue组件文件,并添加以下代码:

<script>
  //Importing Bubble class from the vue-chartjs wrapper
  import { Bubble } from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default {
    extends: Bubble,
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['Data'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [
                {
                  x: 100,
                  y: 0,
                  r: 10
                },
                {
                  x: 60,
                  y: 30,
                  r: 20
                },
                {
                  x: 40,
                  y: 60,
                  r: 25
                },
                {
                  x: 80,
                  y: 80,
                  r: 50
                },
                {
                  x: 20,
                  y: 30,
                  r: 25
                },
                {
                  x: 0,
                  y: 100,
                  r: 5
                }
              ]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  }
</script>

上面的代码与LineChart.vueBarChart.vue文件中的代码相似。 此处的区别在于, Bubble类是代替LineBar导入和扩展的,并且datasets对象对xyz采用不同的值。

在看到气泡图之前,我们还需要做一件事-对于其他图表也VueChartJS.vue :编辑VueChartJS.vue文件,然后将<!--Bubble Chart example-->替换为<bubble-chart></bubble-chart>

见钢笔VUE-chartjs -气泡图由SitePoint( @SitePoint上) CodePen

展示反应性的条形图

我们将用vue-chartjs演示的最后一个示例是如何使用它制作图表,该图表在数据集发生变化时会自动更新。 需要特别注意的是,Chart.js通常不提供此功能,但是vue-chartjs可以提供-在这两个mixin的帮助下:

  • reactiveProp
  • reactiveData

打开src / components文件夹内的Reactive.vue组件文件,然后输入以下代码:

<script>
  //Importing Bar and mixins class from the vue-chartjs wrapper
  import { Bar, mixins } from 'vue-chartjs'
  //Getting the reactiveProp mixin from the mixins module.
  const { reactiveProp } = mixins
  export default Bar.extend({
    mixins: [ reactiveProp ],
    data () {
      return {
        //Chart.js options that control the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      // this.chartData is created in the mixin and contains all the data needed to build the chart.
      this.renderChart(this.chartData, this.options)
    }
  })
</script>

我们在上面的代码中所做的第一件事是导入从vue-chartjs包装器分类的Barmixins并扩展Bar 。 我们还提取reactiveProp混入从mixins模块,用于反应性。

reactiveProp混入扩展图表组件的逻辑,会自动创建一个名为道具chartData ,并增加了一个Vue公司的专家以这个道具。 这次我们没有创建dataset对象,因为所有需要的数据都将在chartData内。

为此,我们需要进一步编辑VueChartJS.vue 。 打开VueChartJS.vue ,然后在components属性之后,添加以下代码:

data () {
  return {
    // instantiating datacollection with null
    datacollection: null
  }
},
created () {
  //anytime the vue instance is created, call the fillData() function.
  this.fillData()
},
methods: {
  fillData () {
    this.datacollection = {
      // Data for the y-axis of the chart
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          // Data for the x-axis of the chart
          data: [this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt()]
        }
      ]
    }
  },
  getRandomInt () {
    // JS function to generate numbers to be used for the chart
    return Math.floor(Math.random() * (50 - 5 + 1)) + 5
  }
}

让我们看一下上面的代码。 在data对象,我们返回datacollection ,这是设置为null ,而在created方式,我们称之为fillData()随时随地创建组件实例。 fillData函数将在methods对象中创建。

methods对象中,我们创建了一个名为fillData的函数。 此函数创建一个datacollection对象,该对象包含一个label数组(x轴的datasets )和一个datasets数组,该datasets包含y轴所需的data数组。

注意: data数组的内容是一个getRandomInt函数,它将为我们生成一个随机数。

最后,要显示我们的图表并查看反应性是否有效,请使用以下内容替换<!--Reactivity Line Chart example-->

<reactive :chart-data="datacollection"></reactive>
<button class="button is-primary" @click="fillData()">Randomize</button>

我们正在使用我们创建的reactive组件,并将datacollection的内容传递到chart-data道具以显示图表。 我们还有一个按钮,可以在fillData()单击时调用fillData()方法。

导航到应用程序中的/chartjs路由以查看新图表,然后单击“ 随机化”按钮以查看图表,并再次使用新数据实时自动呈现。

见钢笔VUE-chartjs -反应条形图由SitePoint( @SitePoint上) CodePen

用vue图表制作图表

vue-charts采用了与vue-chartjs不同的方法来构建图表。 它不需要您创建单独的组件来处理数据和呈现图表。 可以在Vue实例中实例化图表所需的所有数据,如下所示:

data () {
  return {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    dataset: [65, 59, 80, 81, 56, 55, 40]
  }
}

而且,我们可以在模板中使用<chartjs-line></chartjs-line>轻松显示折线图,使用<chartjs-line></chartjs-line> <chartjs-bar></chartjs-bar> ,而使用<chartjs-radar></chartjs-radar>

在继续之前,我们需要在全球范围内注册vue-charts。 在src文件夹中打开main.js ,并在现有import语句下添加以下代码行:

import 'chart.js'
import 'hchs-vue-charts'

Vue.use(window.VueCharts)

在这里,我们从node_modules文件夹导入Chart.js库和hchs-vue-charts包装器,并在Vue.use(window.VueCharts)全局注册。

现在让我们开始使用vue-charts 。 打开我们之前创建的VueCharts.vue文件,然后输入以下代码:

<template>
  <section class="container">
    <h1>Demo examples of vue-charts</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <!--Line Chart Example-->
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart Example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Radar Chart</h3>
        <!--Radar Chart Example-->
      </div>
      <div class="column">
        <h3>Data Binding Line Chart</h3>
        <!--Data Binding Line Chart Example-->
      </div>
    </div>
  </section>
</template>

<script>
  export default {
    name: 'VueCharts',
    data () {
      return {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        dataset: [65, 59, 80, 81, 56, 55, 40]
      }
    }
  }
</script>

在上面的代码块中,我们为图表创建了占位符,我们要做的就是开始放入它们。

然后,我们在script部分的data对象中添加了将用于各种图表的标签和数据。

现在开始创建图表。

折线图

要添加折线图,我们<chartjs-line></chartjs-line>就是在VueCharts.vue文件的模板部分中添加<chartjs-line></chartjs-line>代替注释<!--Line Chart Example--> VueCharts.vue 。 我们不需要导入任何组件,因为vue-charts已在main.js全局main.js

条形图

对于条形图,我们也是如此。 在VueCharts.vue文件的模板部分中,在注释<!--Bar Chart Example-->位置添加<chartjs-bar></chartjs-bar>

雷达图

我们对雷达图也是如此。 在VueCharts.vue文件的模板部分中,在注释<!--Radar Chart Example--> <chartjs-radar></chartjs-radar>的位置添加<chartjs-radar></chartjs-radar>

完成后,您可以导航到/charts并查看我们刚刚创建的图表。

请参阅CodePenSitePoint@SitePoint )的Pen vue-charts演示

折线图的数据绑定示例

vue-charts数据绑定与vue-chartjs ,尽管每当数据集更改时vue-charts图表都会自动更新图表。

为了测试这一点,我们将创建一个名为addData的函数并将其添加到组件的methods对象中:

methods: {
  addData () {
    this.dataset.push(this.dataentry)
    this.labels.push(this.datalabel)
    this.datalabel = ''
    this.dataentry = ''
  }
}

addData方法将数据表单输入和标签表单输入(我们将很快添加)的当前值推送到当前数据集。 现在,让我们添加组件以及添加新数据和标签的表单。

在注释<!--Data Binding Line Chart Example-->处添加以下代码:

<form @submit.prevent="addData">
  <input placeholder="Add a Data" v-model="dataentry">
  <input placeholder="Add a Label" v-model="datalabel">
  <button type="submit">Submit</button>
</form>
<chartjs-line :labels="labels" :data="dataset" :bind="true"></chartjs-line>

上面的代码是一种表格,允许您键入数据和标签的值,然后提交表格。 该图表将使用最新条目自动呈现。

请参阅CodePenSitePoint@SitePoint )的Pen vue-charts数据绑定

用vue-chartkick制作图表

vue-chartkick是一个Vue包装器,可让您用一行创建漂亮的图表。 我们将通过四个示例演示该库的用法。 我们将创建折线图,条形图,散点图,并使用下载功能(可下载图表)。

在处理图表数据集所需的数据方面, vue-chartkick提供了两种选择。 我们可以做类似<bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>类的事情,在其中将数据内联添加,或<line-chart :data="chartData"></line-chart> ,我们在Vue数据对象中声明chartData数组,如下所示:

data () {
  return {
    chartData: [['Jan', 44], ['Feb', 27], ['Mar', 60], ['Apr', 55], ['May', 37], ['Jun', 40], ['Jul', 69], ['Aug', 33], ['Sept', 76], ['Oct', 90], ['Nov', 34], ['Dec', 22]]
  }
}

让我们开始使用vue-chartkick。 在继续之前,请打开src文件夹中的main.js文件,并添加以下代码:

import Chartkick from 'chartkick'
import VueChartkick from 'vue-chartkick'

Vue.use(VueChartkick, { Chartkick })

在这里,我们导入Chartkick库和vue-chartkick从包装node_modules并在全球注册它Vue.use(VueChartkick, { Chartkick })

要开始使用vue-chartkick创建图表,请打开我们之前创建的VueChartKick.vue文件,并添加以下代码:

<template>
  <section class="container">
    <h1>Demo examples of vue-chartkick</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <!--Line Chart example-->
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Scatter Chart</h3>
        <!--Scatter chart example-->
      </div>
      <div class="column">
        <h3>Downloadable Line Chart</h3>
        <!--Downloadable line chart-->
      </div>
    </div>
  </section>
</template>

<script>
  export default {
    name: 'VueChartKick',
    data () {
      return {
        chartData: [['Jan', 44], ['Feb', 27], ['Mar', 60], ['Apr', 55], ['May', 37], ['Jun', 40], ['Jul', 69], ['Aug', 33], ['Sept', 76], ['Oct', 90], ['Nov', 34], ['Dec', 22]]
      }
    }
  }
</script>

在上面的代码块中,我们再次为将要创建的不同类型的图表创建了占位符,而我们要做的就是开始放入它们。

然后,我们创建了chartData数组,该数组保存了将用于script部分内部data对象中各种图表的data 。 现在开始创建图表。

折线图

使用vue-chartkick创建折线图非常简单明了。 您所要做的就是引入vue-chartkick line-chart组件,并确定要使用的数据集-像这样: <line-chart :data="chartData"></line-chart> 。 在这种情况下, data属性将设置为Vue data对象中的chartData数组。

因此,将VueChartKick.vue文件中的注释<!--Line Chart example--> VueChartKick.vue<line-chart :data="chartData"></line-chart> ,折线图现在应该可以很好地显示。

条形图

我们可以像创建上面的折线图一样创建条形图。 但是在这种情况下,我们将尝试一些不同的方法。 代替使用chartData数组作为数据集,我们将数据集添加到props内部,如下所示: <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>

<bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>替换VueChartKick.vue文件中的注释<!--Bar Chart example--> <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart> ,您的条形图应立即显示。

散点图

散点图的工作方式也类似于上面的折线图和条形图。 用<scatter-chart :data="[[174.0, 80.0], [176.5, 82.3], [180.3, 73.6]]"></scatter-chart> <!--Scatter Chart example-->替换为VueChartKick.vue文件中的注释<!--Scatter Chart example--> <scatter-chart :data="[[174.0, 80.0], [176.5, 82.3], [180.3, 73.6]]"></scatter-chart> ,您的散点图应立即显示。

下载图表

vue-chartkick具有vue-chartjsvue-charts缺少的漂亮功能:创建可下载图表的功能。 将图表设置为可下载后,用户可以轻松地将图表另存为图像。 那么这是如何工作的呢? 让我们用折线图检查一下:

<line-chart :data="chartData" :download="true"></line-chart>

我们将:download属性设置为true,这意味着该图表是可下载的。 就这样!

<line-chart :data="chartData" :download="true"></line-chart>替换VueChartKick.vue文件中的注释<!--Downloadable line chart--> <line-chart :data="chartData" :download="true"></line-chart>以查看和测试下载功能在您的应用上。 您可以将鼠标悬停在新图表上以查看下载按钮。

演示版

见笔VUE-chartkick演示由SitePoint( @SitePoint上) CodePen

比较

因此,现在我们已经完成了Chart.js的三个Vue.js包装器,每个包装器的优缺点是什么?

Vue图表

在三个包装器中, vue-chartjs可能是功能最强大的。 它为灵活性提供了很大的空间,并且还具有反应性功能(如果数据发生更改,可以自动重新绘制图表的功能)。

包装程序的一个缺点是,由于可用的各种选项,并且由于必须创建一个外部文件来保存包装程序的配置,因此在开始时配置图表可能会有些复杂。

视点表

vue-chartjs是一个很好的Chart.js包装器。 设置非常简单,这与vue-chartjs不同。 它不需要您创建单独的组件来处理数据和绘制图表。 如上例所示,可以在Vue实例中实例化图表所需的所有数据。 它还具有反应性功能(如果数据集发生更改,则可以自动呈现图表的功能),而无需混合。

Vue-Chartkick

vue-chartkick也是一个很好的Chart.js包装器。 它可能是三个Chart.js包装器中使用起来最简单的包装器。

可以在vue-chartkick以两种不同的方式添加图表数据集。 我们可以做类似<bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>类的事情,在其中将数据内联添加,或<line-chart :data="chartData"></line-chart> ,我们在Vue数据对象中声明chartData数组,如上面的示例所示。 它还具有出色的功能,可让您以图表的形式下载图表,而其他包装程序则缺少这些功能。

vue-chartkick的唯一缺点是它不支持开箱即用的反应性。

结论

在本文中,我介绍了Chart.js的各种Vue包装器,还演示了如何使用它们的每个示例为您的下一个Web项目创建漂亮的图表的示例。

该教程的源代码可在GitHub上获得 ,如果您想观看该教程的实时演示,也可以在此处查看

From: https://www.sitepoint.com/creating-beautiful-charts-vue-chart-js/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js 是一个流行的 JavaScript 框架,用于构建用户界面。TypeScript 可以为 JavaScript 提供静态类型检查和更好的代码提示功能。这两个工具结合使用可以帮助您创建精美的流程图。 以下是创建流程图的基本步骤: 1. 安装 Vue.js 和 TypeScript 在终端中使用以下命令安装 Vue.js 和 TypeScript: ``` npm install vue npm install typescript ``` 2. 创建一个 Vue.js 组件 使用 Vue.js 创建一个组件来包含流程图。这个组件将渲染流程图并处理用户的输入。 ```typescript <template> <div> <!-- 流程图渲染区域 --> </div> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component({ name: 'Flowchart' }) export default class Flowchart extends Vue { // 组件逻辑 } </script> <style lang="scss"></style> ``` 3. 定义流程图节点和连接 定义节点和连接的类型,并创建一个节点列表和连接列表。这些列表应该在组件的 data 属性中定义。 ```typescript interface Node { id: number; name: string; x: number; y: number; } interface Link { source: number; target: number; } @Component({ name: 'Flowchart' }) export default class Flowchart extends Vue { nodes: Node[] = [ { id: 1, name: 'Start', x: 100, y: 100 }, { id: 2, name: 'Step 1', x: 200, y: 200 }, // ... ]; links: Link[] = [ { source: 1, target: 2 }, { source: 2, target: 3 }, // ... ]; } ``` 4. 渲染流程图 使用 SVG 渲染流程图。为每个节点创建一个圆圈,并连接它们以表示流程。 ```typescript <template> <div> <svg> <g v-for="node in nodes" :key="node.id"> <circle :cx="node.x" :cy="node.y" r="30"></circle> <text :x="node.x" :y="node.y">{{node.name}}</text> </g> <path v-for="link in links" :key="link.source + '-' + link.target" :d="linkPath(link)"></path> </svg> </div> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; interface Node { id: number; name: string; x: number; y: number; } interface Link { source: number; target: number; } @Component({ name: 'Flowchart' }) export default class Flowchart extends Vue { nodes: Node[] = [ { id: 1, name: 'Start', x: 100, y: 100 }, { id: 2, name: 'Step 1', x: 200, y: 200 }, // ... ]; links: Link[] = [ { source: 1, target: 2 }, { source: 2, target: 3 }, // ... ]; linkPath(link: Link): string { const source = this.nodes.find((node) => node.id === link.source); const target = this.nodes.find((node) => node.id === link.target); const dx = target.x - source.x; const dy = target.y - source.y; const dr = Math.sqrt(dx * dx + dy * dy); return `M${source.x},${source.y}A${dr},${dr} 0 0,1 ${target.x},${target.y}`; } } </script> <style lang="scss"></style> ``` 5. 添加交互 通过响应用户的鼠标点击和拖拽事件,允许用户交互式地编辑流程图。 ```typescript <template> <div> <svg> <g v-for="node in nodes" :key="node.id"> <circle :cx="node.x" :cy="node.y" r="30" :class="{ selected: selectedId === node.id }" @mousedown="startDrag(node, $event)" @mouseup="stopDrag" ></circle> <text :x="node.x" :y="node.y">{{node.name}}</text> </g> <path v-for="link in links" :key="link.source + '-' + link.target" :d="linkPath(link)"></path> </svg> </div> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; interface Node { id: number; name: string; x: number; y: number; } interface Link { source: number; target: number; } @Component({ name: 'Flowchart' }) export default class Flowchart extends Vue { nodes: Node[] = [ { id: 1, name: 'Start', x: 100, y: 100 }, { id: 2, name: 'Step 1', x: 200, y: 200 }, // ... ]; links: Link[] = [ { source: 1, target: 2 }, { source: 2, target: 3 }, // ... ]; selectedId: number | null = null; startDrag(node: Node, event: MouseEvent): void { this.selectedId = node.id; const element = event.target as SVGGraphicsElement; element.addEventListener('mousemove', this.drag); } stopDrag(): void { this.selectedId = null; document.removeEventListener('mousemove', this.drag); } drag(event: MouseEvent): void { if (this.selectedId) { const node = this.nodes.find((n) => n.id === this.selectedId); if (node) { node.x += event.movementX; node.y += event.movementY; } } } linkPath(link: Link): string { const source = this.nodes.find((node) => node.id === link.source); const target = this.nodes.find((node) => node.id === link.target); const dx = target.x - source.x; const dy = target.y - source.y; const dr = Math.sqrt(dx * dx + dy * dy); return `M${source.x},${source.y}A${dr},${dr} 0 0,1 ${target.x},${target.y}`; } } </script> <style lang="scss"> .selected { fill: pink; } </style> ``` 现在,您已经创建了一个基本的流程图。您可以自定义节点和连接的外观,并使用更高级的技术来添加更多功能,如撤销和重做,输入和输出等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值