我正在尝试从 JSON 文件 a.json 中对 JSON 数组进行排序。
数组是这样来的:
{"data":
[
{"exception":"",
"name":"Data Server1",
"alias":"TOR-Server",
"delayed":"NO",
},
{"exception":"",
"name":"Data Server2",
"alias":"FRA-Server",
"delayed":"NO",
}
]
我需要根据来自 Vue JS 的 JSON 文件的“别名”对数据进行排序。
这是我在 Vue JS 中显示的 Javascript 代码
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
json: null
},
computed: {
sorted: function() {
setTimeout(function() {
var app = this.app.json
if (app.length >= 6)
return app;
}, 5000);
}
},
methods: {
toggleClass(){
if (this.failed == true){
this.failed = false;
}
else
{
this.failed = true;
}
}
}
但是 Sorted 函数不起作用,如果我尝试显示排序数组中的服务器,我会收到一个空白页面。
我在 HTML 页面中的 for 循环是:
<div class="mainbutton" v-for="(server, index) in json.data ">
希望这是有道理的,我可以让它发挥作用。
最佳答案
您可以使用 Array.sort
在计算中,返回排序后的数组。
例如,按 name
对数组的项目进行排序属性(property),您可以调用:this.json.sort((t1,t2) => t1.name < t2.name ? -1 : 1)
.
这是一个工作片段:
var app = new Vue({
el: '#app',
data: {
json: [
{
"exception": "",
"name": "Data Server3",
"alias": "TOR-Server",
"delayed": "NO",
},
{
"exception": "",
"name": "Data Server1",
"alias": "TOR-Server",
"delayed": "NO",
},
{
"exception": "",
"name": "Data Server2",
"alias": "FRA-Server",
"delayed": "NO",
}
]
},
computed: {
sortedJson: function() {
return this.json.sort((t1,t2) => t1.name < t2.name ? -1 : 1);
},
sorted: function() {
setTimeout(function() {
var app = this.app.json
if (app.length >= 6)
return app;
}, 5000);
}
},
methods: {
toggleClass() {
if (this.failed == true) {
this.failed = false;
} else {
this.failed = true;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
<div class="mainbutton" v-for="(server, index) in sortedJson ">
{{server.name }}
</div>
</div>
关于javascript - VueJS2 排序 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46990707/