我正在创建一个条形图来显示特定位置的犯罪数据。您可以使用选择来选择位置,这会更新位置获取中的经度和纬度。
我循环遍历数据以创建一个对象,其中包含犯罪类型和每个类别的每种犯罪数量。然后我将这些数据传递给子组件(条形图)进行显示。但是,选择新位置时,数据似乎不会传递到子组件,因此条形图不会显示任何数据。
我的代码: 应用程序.vue
<template>
<div>
<h1>Crime Rates in {{selectedLocation}}</h1>
<BarChartNew v-if="theData" :dataset="theData" :labels="labels" />
<select name="location" @change="getLocation($event, this.locations)" v-model="selectedLocation">
<option v-for="(coordinates, location) in locations" :key="location" :value="location">
{{location}}
</option>
</select>
</div>
</template>
<script>
import { locations } from "@/middleware/locations.js";
import BarChartNew from "./components/barChartNew.vue";
export default {
name: "App",
components: { BarChartNew },
data() {
return {
crimes: null,
locations,
theData: [],
labels: [],
selectedLocation: 'Bristol',
categoryObject: {}
};
},
methods: {
async fetchData(selectedLocation) {
const lat = this.locations[selectedLocation].lat
const lng = this.locations[selectedLocation].lng
try {
const response = await fetch(
`https://data.police.uk/api/crimes-street/all-crime?lat=${lat}&lng=${lng}&date=2023-01`,
{
"Content-Type": "text/plain",
}
);
const data = await response.json();
const allCategories = data.map((item) => item.category);
for (let item in data){
this.categoryObject.hasOwnProperty(data[item].category)
? this.categoryObject[data[item].category]++
: this.categoryObject[data[item].category] = 1
}
this.labels.push(...Object.keys(this.categoryObject))
this.theData = Object.values(this.categoryObject)
} catch (e) {
console.error(e);
}
},
getLocation(event){
const selectedLocation = event.target.value
this.labels = [];
this.fetchData(event.target.value)
return { selectedLocation }
}
},
mounted() {
this.fetchData(this.selectedLocation);
},
}
</script>
barChartNew.vue:
<template>
<div>
<Bar
:data="chartData"
:options="chartOptions"
/>
</div>
</template>
<script>
import { Bar } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'
ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)
export default {
components: { Bar },
props: {
dataset: {
type: Array,
required: false,
},
labels: {
type: Array,
required: true,
},
},
data() {
return {
chartData: {
labels: this.labels,
datasets: [
{
borderColor: "#f6b09e",
backgroundColor: "rgb(246, 176, 157)",
label: "crimes",
data: this.dataset,
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true },
title: { display: true, text: "Crimes 🥷🏻 in your area" },
},
},
};
},
};
</script>
chartData
有两个问题:
chartData
对象和
chartData.datasets
数组以检测变化并重绘图表
chartData
转换为计算属性来解决这两个问题:
computed: {
chartData(){
return {
labels: this.labels,
datasets: [
{
borderColor: "#f6b09e",
backgroundColor: "rgb(246, 176, 157)",
label: "crimes",
data: this.dataset,
},
],
}
}
}
这是一个简化的