You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中Axios.get获取数组后v-for失效及Axios.post参数写法疑问

Vue + Axios 问题解答

问题1:Axios获取数据后表格不渲染

问题根源

  1. 未在<script setup>中声明响应式的form变量,模板里引用的form不存在,导致v-for无数据可循环。
  2. Axios请求成功后仅打印数据并return res.data,未将数据赋值给任何与模板关联的变量。
  3. :key="params"直接用整个对象作为key不符合Vue规范,易引发渲染异常,建议使用数据中的唯一标识(如id)。

修正代码

<template>
  <table>
    <tr v-for="item in formList" :key="item.id"> <!-- 若数据无id,可替换为其他唯一字段 -->
      <td>{{ item.title }}</td>
      <td>{{ item.company }}</td>
      <td>{{ item.company_url }}</td>
      <td>{{ item.location }}</td>
      <td>{{ item.description }}</td>
      <td>{{ item.date_posted }}</td>
    </tr>
  </table>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';

// 声明响应式数组存储接口返回数据
const formList = ref([]);

// 组件挂载后发起请求
onMounted(async () => {
  try {
    const res = await axios.get("API_URL/list", {
      params: {
        title: "",
        company: "",
        company_url: "",
        location: "",
        description: "",
        date_posted: "",
      }
    });
    console.log(res.data);
    formList.value = res.data; // 将接口数据赋值给响应式变量
  } catch (err) {
    console.error("请求失败:", err);
  }
});
</script>

问题2:Axios.post参数封装写法是否正确

你的写法本身是正确的,但可以简化:无需逐个属性赋值,直接复制整个form对象即可(前提是form的属性与接口要求的参数完全匹配)。

优化后代码

const state = reactive({
  form: {
    title: "",
    company: "",
    company_url: "",
    location: "",
    description: "",
    date_posted: ""
  },
});

const formCreate = async () => {
  // 扩展运算符快速复制表单数据
  const postdata = { ...state.form };
  
  // 补充Axios.post调用及异常处理
  try {
    const res = await axios.post("API_URL/create", postdata);
    console.log("提交成功:", res.data);
    // 可添加成功后的逻辑,如页面跳转、表单重置等
  } catch (err) {
    console.error("提交失败:", err);
  }
};

内容的提问来源于stack exchange,提问作者bxeom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 13:03:24