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 已经是排序后的数组。

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

排序效果

相关推荐
上海合宙LuatOS6 天前
LuatOS核心库API——【json 】json 生成和解析库
java·前端·网络·单片机·嵌入式硬件·物联网·json
敲代码的柯基6 天前
一篇文章理解tsconfig.json和vue.config.js
javascript·vue.js·json
万物得其道者成7 天前
前端大整数精度丢失:一次踩坑后的实战解决方案(`json-bigint`)
前端·json
Ai runner7 天前
Show call stack in perfetto from json input
java·前端·json
ID_180079054737 天前
淘宝商品详情API请求的全场景,带json数据参考
服务器·数据库·json
恒云客8 天前
python uv debug launch.json
数据库·python·json
wanderist.8 天前
从 TCP 到 JSON:一次 FastAPI + LLM 生产环境 “Unexpected end of JSON input” 的底层剖析
tcp/ip·json·fastapi
享誉霸王9 天前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5
今心上9 天前
关于json的理解测试!!
开发语言·json
强子感冒了10 天前
JSON和XML学习笔记
xml·学习·json