如何在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>
错误原因
headings是then回调内部定义的局部变量,外部作用域本身无访问权限- 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
相关产品推荐
相关产品推荐

