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

如何在Composition API中将Axios响应变量返回至Vue组件根级

Vue3 异步axios请求数据在组件内使用方案

问题报错

尝试从axios.get函数中返回headings数组,在Vue组件的根作用域使用时,触发如下报错:

ReferenceError: headings is not defined

初始错误代码

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

const homePage = ref({
    heading: "",
    content: "",
    image: ""
});

axios.get('/home')
    .then(res => {
        const data = res.data[res.data.length - 1]
        const headings = {
            en: data['heading_(en)'],
            de: data['heading_(de)'],
            ar: data['heading_(ar)'],
        }
        return headings;
    })

console.log(headings);

</script>

错误原因

  1. headings是then回调内部定义的局部变量,外部作用域本身无访问权限
  2. axios是异步请求,根作用域的console.log执行时,请求还未返回结果,then回调尚未触发,自然不存在对应的变量

最优解决方案

使用Vue3的reactive定义响应式状态,在axios请求的then回调中直接给状态赋值即可:

<script setup>
import {reactive} from 'vue';

const state = reactive({
    headings: {},
    content: {},
    image: ""
})

axios.get('/home')
    .then(res => {
        const data = res.data[res.data.length - 1]

        state.headings = {
            en: data['heading_(en)'],
            de: data['heading_(de)'],
            ar: data['heading_(ar)'],
        }

        console.log(state.headings.en)
    })

</script>

模板调用方式

<h2>{{ state.headings.en }}</h2>

补充说明

axios是异步请求,要把请求返回的值直接暴露到组件根作用域实现成本很高,绝大多数业务场景都不需要这么做,在then回调内给响应式状态赋值就完全可以满足使用需求。

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:54:05