Home  >  Q&A  >  body text

Make a <select> method for selecting drawing chart files

<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粉022140576P粉022140576425 days ago517

reply all(1)I'll reply

  • P粉107991030

    P粉1079910302023-08-21 09:01:01

    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;
        });
      },
    },
    

    reply
    0
  • Cancelreply