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

Vue项目中如何使用useAxios传递数据发起PUT请求?

使用VueUse useAxios发起PUT请求传递请求数据的正确方式

首先明确核心误区:useAxios返回的data是用来存储后端响应结果的响应式变量,并非设置请求体的入口。请求体数据需要通过axios配置对象的data字段传递,以下是两种正确实现方式:

方式一:初始化时配置请求参数

适合请求地址、方法相对固定的场景:

<script setup>
import { useAxios } from '@vueuse/integrations/useAxios'
import axios from 'axios'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const post = ref(/* 你的post表单数据 */)
const notification = ref('')
const error = ref('')

// 初始化时配置PUT请求的地址、方法与请求体
const { execute, isError } = useAxios(
  `/blog/posts/${route.params.postID}/`,
  {
    method: 'PUT',
    data: post.value
  },
  axios
)

// 执行请求并处理结果
const updatePost = async () => {
  try {
    await execute()
    notification.value = 'Post Updated!'
  } catch () {
    error.value = 'Failed to update post'
  }
}
</script>

方式二:动态调用execute时传入请求体

适合需要动态修改请求地址或数据的场景:

<script setup>
import { useAxios } from '@vueuse/integrations/useAxios'
import axios from 'axios'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const post = ref(/* 你的post表单数据 */)
const notification = ref('')
const error = ref('')

// 初始化时仅传入axios实例,留空请求配置
const { execute } = useAxios(axios)

const updatePost = async () => {
  try {
    // execute第二个参数为axios配置对象,请求体放在data属性中
    await execute(`/blog/posts/${route.params.postID}/`, {
      method: 'PUT',
      data: post.value
    })
    notification.value = 'Post Updated!'
  } catch () {
    error.value = 'Failed to update post'
  }
}
</script>

你之前的错误点说明

  • 直接赋值data.value = post无效:data是响应式的响应结果容器,不是请求入参的设置项。
  • 直接将post传入execute报错:execute的第二个参数必须是完整的axios配置对象,请求体必须嵌套在data字段中传递。

内容的提问来源于stack exchange,提问作者Andrew R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:15:38