Make a <select> method for selecting drawing chart files
P粉022140576
P粉022140576 2023-08-20 10:08:18
0
1
574
<p>I have a chart drawn using data from an external file. Now I want a select box where the user can select the file to read. This way the chart can change dynamically. How can I use vue and chartjs to achieve this functionality? </p> <p>Currently, I import data in Home like this:</p> <pre class="brush:php;toolbar:false;"><template> <div class="home"> <Graph :vul_data="data"/> </div> </template> <script> import { Component, Prop, Vue } from 'vue-property-decorator'; import Graph from '@/components/Graph.vue'; import {data} from '@/data/dataFile.js' @Component({ components: { Graph, }, }) export default class HomeView extends Vue { data() { return { data: data, } } } </script></pre> <p>The data for each file is as follows: </p> <pre class="brush:php;toolbar:false;">export const data = { "points": { "line1": { "x": [ -11, -11, ], "y": [ 7, 8, ] }, }, }</pre> <p>The components are as follows:</p> <pre class="brush:php;toolbar:false;"><template> <div> <canvas id="myChart"></canvas> </div> </template> <script> import Chart from 'chart.js/auto'; export default{ name: "Graph", props: ["vul_data"], mounted(){ const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'scatter', data: { datasets: [{ label: 'Line 1', data:[ {x: this.vul_data.points.line1.x[0], y: this.vul_data.points.line1.y[0]}, {x: this.vul_data.points.line1.x[1], y: this.vul_data.points.line1.y[1]}, ], }, ] }, }); } } </script> <style> </style></pre>
P粉022140576
P粉022140576

reply all(1)
P粉107991030

You can use the <select> tag where the options contain a value equal to the name of your .js file. When the selection changes, run a method that dynamically imports the file and assigns the imported data to variables you pass as properties to the Graph component. Simple sample code:

<select @change="selectFile">
  <option value="dataFile1">文件一</option>
  <option value="dataFile2">文件二</option>
</select>
<Graph :vul_data="data" />
data() {
  return {
    data: null,
  };
},
methods: {
  selectFile(e) {
    import(`@/data/${e.target.value}.js`).then((res) => {
      this.data = res.data;
    });
  },
},
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template