npm install vue npm install echarts npm install axios
css/ -- style.css js/ -- main.js php/ -- data.php index.html
In the css directory, create the style.css file for style definitions.
In the js directory, create the main.js file to handle Vue.js logic.
In the php directory, create the data.php file to simulate back-end data.
index.html serves as the entry point for the project.
<?php $data = [ ['name' => 'A', 'value' => 100], ['name' => 'B', 'value' => 200], ['name' => 'C', 'value' => 300], ['name' => 'D', 'value' => 400], ['name' => 'E', 'value' => 500] ]; echo json_encode($data); ?>
The code above uses the json_encode function to convert the array into a JSON string and returns it to the front-end.
import Vue from 'vue'; import axios from 'axios'; import echarts from 'echarts'; new Vue({ el: '#app', data: { chartData: [] }, created() { this.fetchData(); }, methods: { fetchData() { axios.get('./php/data.php') .then(response => { this.chartData = response.data; this.drawChart(); }) .catch(error => { console.log(error); }); }, drawChart() { var chart = echarts.init(document.getElementById('chart-container')); var option = { title: { text: 'Data Statistical Chart' }, xAxis: { type: 'category', data: this.chartData.map(item => item.name) }, yAxis: { type: 'value' }, series: [{ data: this.chartData.map(item => item.value), type: 'bar' }] }; chart.setOption(option); } } });
This code uses axios to fetch the back-end data and echarts to generate the bar chart.
<meta charset="utf-8"> <title>PHP and Vue.js Tutorial</title> <link rel="stylesheet" type="text/css" href="./css/style.css"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script> <script src="./js/main.js"></script> <div id="app"> <div id="chart-container"></div> </div>
In this HTML code, we first include the Vue.js, Axios, and Echarts libraries. We then create a div with the id app as the root element for Vue.js and a div with the id chart-container to display the chart.
npm run serve
Once successful, visit http://localhost:8080 to view the generated chart.