WordPress, Vue and Chart.js

Prerequisites

Custom Fields

Sample data. Published posts on medium and tumblr over the last 7 years

Make it vue


npm install vue-chartjs -D

Create a bar chart component

import { Bar } from ‘vue-chartjs’export default Bar.extend({
props: [“data”, “options”],
mounted () {
this.renderChart(this.data, this.options)
}
})
{
labels: ['X Axis Label 1', 'X Axis Label 2'],
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: [40, 20, 12]
}
]
}
import { Bar } from 'vue-chartjs'export default Bar.extend({
props: ['labels', 'datasets'],
computed: {
'chartdata': function () {
return {
labels: this.labels,
datasets: this.datasets
}
}
},
mounted () {
this.renderChart(this.chartdata,
{responsive: true, maintainAspectRatio: false})
}
})

Template

<?php if(have_rows('datasets')): ?>
<?php
$datasets = [];
?>
<?php while ( have_rows('datasets') ) : the_row();
$datasets[] = array(
'label' => get_sub_field('dataset_label'),
'backgroundColor' => get_sub_field('dataset_color'),
'data' => explode(', ', get_sub_field('dataset_data'))
);
endwhile;
$labels = get_field('x_axis');
$legend = get_field('legend');
$chartDatasets = htmlspecialchars(json_encode($datasets));
$chartLabels = htmlspecialchars(json_encode(explode(', ', $labels)));
?><section class="chart-box text">
<div class="text__wrapper">
<bar-example
:labels="<?= $chartLabels; ?>"
:datasets="<?= $chartDatasets; ?>" >
</bar-example>
</div>
</section>
<?php endif; ?>

--

--

--

#Freelance Developer — #Blogger, #Student, #Tea addicted, likes #photography #indie #gamedev #webdev

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Redux. What it is. Why?When? How to use.

IFTTT filters are actually quite capable

Adding Tooltip to React-Native Charts

JavaScript

An Annoy Tiny Difference Between JavaScript and Python: Can't use the dot operator to get a value…

4 Practices to Help You Understand array.reduce()

Algorithms 101: House Robber in JavaScript

What I Learned Refactoring Terrapin with Redux

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jakub Juszczak

Jakub Juszczak

#Freelance Developer — #Blogger, #Student, #Tea addicted, likes #photography #indie #gamedev #webdev

More from Medium

Getting Started with Vue

Vue JS Project Based Learning | Project 1

One year of experience with Vue.js

CORS Preflight Did Not Succeed on nuxt js/ vuejs