Make a <select> method for selecting drawing chart files
P粉022140576
2023-08-20 10:08:18
<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>
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: