vue3 ajax获取json数组排序举例

使用axios获取接口数据

可以在代码中安装axios包,并写入到package.json文件:

bash 复制代码
npm install axios -S

接口调用代码举例如下:

javascript 复制代码
const fetchScore = async () => {
    try {
        const res = await axios.get(`http://127.0.0.1:8000/score/${userInput.value}`);
        if (res.status !== 200) return;
        data.value = res.data;
    } catch (error) {
        console.log(error);
    };         
}

后台代码如下:

python 复制代码
@app.get("/score/{count}")
def get_score(count: int):
    if count <= 0: return {}
    result = []
    for i in range(count):
        result.append({"number": i+1, "score": random.uniform(0.0, 100.0)})
    return result 

数据获取效果如下:

json数组进行排序

Vue 3 中对数据进行排序,可以通过在组件的 setup 函数中定义一个计算属性或方法来实现。

1. 使用计算属性排序

javascript 复制代码
<script setup>
import AppLayout from '../components/AppLayout.vue';
import axios from 'axios';
import { ref, computed } from 'vue';

const data = ref([]);
const userInput = ref('')

const sortedData = computed(() => {
  return data.value.slice().sort((a, b) => b.score - a.score);
});

const fetchScore = async () => {
    try {
        const res = await axios.get(`http://127.0.0.1:8000/score/${userInput.value}`);
        if (res.status !== 200) return;
        data.value = res.data;
    } catch (error) {
        console.log(error);
    };         
}
</script>

<template>
    <AppLayout>
      <h1>Score</h1>
      <div>
        <label for="user-input">Enter a number:</label>
        <input id="user-input" v-model.number="userInput" type="number" placeholder="Type a number...">
      </div> 
      <button @click="fetchScore">Fetch Score</button>     
      <p v-if = "data.length > 0">Score list:</p>
      <ul v-if="data.length > 0">
        <li v-for="item in data" :key="item.number">{{ item.number + ": " + item.score }}</li>
      </ul>
      <p v-if="sortedData.length > 0">Sorted Score list:</p>
      <ul v-if="sortedData.length > 0">
        <li v-for="item in sortedData" :key="item.number">{{ item.number + ": " + item.score }}</li>
      </ul>
    </AppLayout>
</template>

2. 直接修改ajax方法所获得的数据

以上述代码为例,可以在 fetchScore 方法中对数据进行排序后再赋值给 data

代码示例如下:

javascript 复制代码
<script setup>
import AppLayout from '../components/AppLayout.vue';
import axios from 'axios';
import { ref } from 'vue';

const data = ref([]);

const fetchScore = async () => {
  try {
    const res = await axios.get(`http://127.0.0.1:8000/score/${userInput.value}`);
    if (res.status !== 200) return;
    data.value = res.data.sort((a, b) => a.score - b.score);
  } catch (error) {
    console.log(error);
  }
}
</script>

<template>
  <AppLayout>
    <h1>Score</h1>
    <button @click="fetchScore">Fetch Score</button>
    <p v-if="data.length > 0">Sorted score list:</p>
    <ul v-if="data.length > 0">
      <li v-for="item in data" :key="item.number">{{ item.number + ": " + item.score }}</li>
    </ul>
  </AppLayout>
</template>

3. 方法比较

  • 计算属性:

sortedData 是一个计算属性,它返回 data 数组的一个排序副本。使用 slice() 方法是为了避免直接修改原始数组。

在模板中使用 sortedData 而不是 data,这样每次 data 变化时,sortedData 都会自动重新计算。

  • 直接修改方法:

fetchScore 方法中,获取数据后直接对其进行排序,并将排序后的结果赋值给 data

在模板中直接使用 data,因为 data 已经是排序后的数组。

选择哪种方式取决于你的具体需求和偏好。计算属性适用于需要多次使用的排序逻辑,而方法适用于一次性排序。

排序效果

相关推荐
烟锁池塘柳020 小时前
Conda 创建环境报错:Unable to read repodata JSON file,清华源 pkgs/free 失效解决方法
json·conda
云水一下2 天前
零基础玩转bWAPP靶场(四十五):XSS - Reflected (JSON)
web安全·json·xss·bwapp·reflected
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ3 天前
Spring‑AI Document 对象 JSON 字段详解
人工智能·spring·json
sunywz3 天前
【从零搭建物联网智能充电桩系统】2、自定义二进制协议:设备为什么不用 JSON?
python·物联网·json
灵析表格3 天前
灵析表格手机号处理函数深度分析报告
前端·网络·json·wps·灵析表格·excel公式盒子
猿长大人3 天前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
消失的旧时光-19434 天前
第六篇:Redis Hash——一个用户对象应该保存成 JSON,还是保存成 Hash?
redis·json·哈希算法
SEO_juper4 天前
2026年Schema自动注入实战:用Python批量给1000个页面加上JSON-LD,AI引用率实测提升38%
人工智能·python·json·seo·独立站
Wang's Blog4 天前
AI Agent白手起家37: LangChain 输出解析器实战:文本、JSON、XML 与 Pydantic
xml·langchain·json
灵析表格4 天前
json_ObjectToKV 函数深度研究报告
json·excel·wps·灵析表格·excel公式盒子