使用 vue.js 时数组数据出现问题
2019-08-17
125
我有一个饼图,显示来自我的数组的数据。我还从数据中生成了一个新数组,但它映射不正确。我如何让图表显示人们的工作。图例应该是一组工作(牙医、教师等)的列表,图表应该显示牙医的数量、教师的数量等,或者另一种选择是年龄。图例显示了 3 个不同的年龄,并映射到人员姓名。这两个场景中的任何一个示例都很棒。
new Vue({
el: "#app",
data: {
newarray:[],
location:[],
numbers:[2, 3, 4, 4, 2, 3],
People:[{Name:"Adam", Age:"32",Job:"Dentist"},{Name:"Bill", Age:"22",Job:"Teacher"},{Name:"Peter", Age:"42",Job:"Dentist"}]
},
mounted:function () {
this.newarray = this.People.map(obj => Object.entries(obj)[1]);
},
methods: {
toggle: function(){
console.log([...new Set(this.People.map(p => p.Job))]);
},
mounted:function(){
this.toggle();
}
}
})
<script src="https://unpkg.com/[email protected]/dist/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<h2>Function:</h2>
<pie-chart :data="newarray" legend="bottom"></pie-chart>
<br>
</div>
1个回答
-
使用数据成员来跟踪“姓名”或“工作”
-
使用计算属性来计算项目。您不需要项目的数据成员。
-
最后,您应该使用 groupBy 函数来计算组计数。
function groupBy(list, keyGetter) {
const map = {};
list.forEach((item) => {
const key = keyGetter(item);
const collection = map[key];
if (!collection) {
map[key] = [item];
} else {
collection.push(item);
}
});
return map
}
new Vue({
el: "#app",
data: {
field: 'Age',
location: [],
numbers: [2, 3, 4, 4, 2, 3],
People: [{
Name: "Adam",
Age: "32",
Job: "Dentist"
}, {
Name: "Bill",
Age: "22",
Job: "Teacher"
}, {
Name: "Peter",
Age: "42",
Job: "Dentist"
}]
},
methods: {
toggle: function() {
this.field = this.field == 'Job' ? 'Age' : 'Job'
}
},
computed: {
rows() {
let byGroup = groupBy(this.People, it => it[this.field])
return Object.entries(byGroup).map(en => ([en[0], en[1].length]))
}
}
})
<script src="https://unpkg.com/[email protected]/dist/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<h2>Function:</h2>
<button @click='toggle'>Toggle</button>
<h3>By {{field}}</h3>
<span v-for='row of rows' style='margin:10px;'>{{row[0]}}:{{row[1]}}</span>
<pie-chart :data="rows" legend="bottom"></pie-chart>
<br>
</div>
Steven Spungin
2019-08-17