如何将所选键传递到另一个模板以显示图表?我创建了一个导出多条折线图的模板,其中使用Axios从API中获取数据。
在主页中,我创建了一个下拉菜单,当用户选择一个项目时,所选项目或其值将传递到该图表模板,并且该模板应将图表返回到该所选项目。
// Home component
<template>
<section>
<label>City</label>
<select @change="getArea()" v-model="key" class="custSelect2">
<option :value="0">Select City</option>
<option v-for="data in cityList" :value="data.id">{{ data.city }}</option>
</select>
<label>Area</label>
<select @change="getWard()" v-model="keyArea" class="custSelect2">
<option :value="0">Select Area</option>
<option v-for="data in areaList" :value="data.id">{{ data.area}}</option>
</select>
<label>Ward</label>
<select v-model="Polekey" @change="getPole()" class="custSelect2">
<option :value="0">Select Ward</option>
<option v-for="data in wardList" :value="data.id">{{ data.ward}}</option>
</select>
<label>Pole</label>
<select v-model="PoleSelected" class="custSelect2">
<option :value="0">Select Pole</option>
<option v-for="data in PoleList" :value="data.poleid">{{ data.poleid}}</option>
</select>
<div>
<Areachart />
</div>
</section>
</template>
// Area component
<script>
import { Line } from "vue-chartjs";
export default {
extends: Line,
data() {
return {
dataList: []
};
},
mounted() {
var self = this;
axios
.get("http://172.31.0.114:5008/api/city/data" + this.key) // key is the value that user selected
.then(function(res) {
self.dataList = res.data;
// how to initilize data into below datasets
})
.catch(function(error) {
console.log("Error:", error);
});
this.renderChart(
{
labels: [],
datasets: [
{
label: "Data One",
borderColor: "#FC2525",
backgroundColor: this.gradient,
data: []
},
{
label: "Data Two",
borderColor: "#05CBE1",
data: []
}
]
},
{ responsive: true, maintainAspectRatio: false }
);
}
};
</script>
答案 0 :(得分:1)
_key
传递props
(我假设它的类型为String
,这是必需的); _key
的更改并调用updateChart
方法,因此每当父项更改_key
时,都会进行相应的API校准; updateChart
请求的GET
方法,进行处理,然后重新发送图表。updateChart
钩子中调用mounted
方法以获取初始数据; datasets
中定义data
,以便以后可以更改它们
服务器响应处理程序。_key
属性。// In ParentComponent
<template>
<Areachart :_key="PoleSelected"/>
</template>
<script>
import { Line } from "vue-chartjs";
export default {
extends: Line,
props: {
_key: {
type: String,
required: true
}
},
data() {
return {
datasets: [
{
label: "Data One",
borderColor: "#FC2525",
data: []
},
{
label: "Data Two",
borderColor: "#05CBE1",
data: []
}
]
};
},
watch: {
_key() {
this.updateChart();
}
},
mounted() {
this.updateChart();
},
methods: {
updateChart() {
axios
.get("http://172.31.0.114:5008/api/city/data" + this._key)
.then(res => {
// proccess the response
// I don't know your data model, so i can't write appropriate handler
// for example this.datasets[0].data = res.data[0]
this.renderChart(
{
labels: [],
datasets: this.datasets
},
{ responsive: true, maintainAspectRatio: false }
);
})
.catch(function(error) {
console.log("Error:", error);
});
}
}
};
</script>
答案 1 :(得分:0)
您可以通过组件中的道具传递数据
<Areachart :data="values"/>
或者您可以制作事件总线并随其发送数据。您可以使用$ emit(发送事件)和$ on(捕获事件)