如何从组合API中的Axios Response返回变量到根级?



我想从axios.get函数返回headings数组,并在vue component内的root level上使用它,但当我试图返回它时,它显示:

ReferenceError: headings is not defined

这是script element从我的Vue3 Component:

<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>

编辑:

Thanks toThomas欢风我可以这样做:

<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>

这是最优雅的解决方案,因为reactive对象在处理数组时提供了最干净的框架。像这样从vue component调用它:

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

由于axiosasynchronous,将变量返回到root level更加困难,在我的情况下没有必要。我可以把它输出到then里面

// Better to wrap page states in a reactive object
const state = reactive({
headings: []
})
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)'],
};
})
// Use state.headings before this line,
// Unpack it and you can directly use headings in template 
const {headings} = toRefs(state);

扩展我的评论:

<script setup>
import { reactive } from 'vue';
const homePage = reactive({
headings: {},
content: '',
image: ''
});
axios.get('/home')
.then(res => {
const data = res.data[res.data.length - 1]
homePage.headings = {
en: data['heading_(en)'],
de: data['heading_(de)'],
ar: data['heading_(ar)'],
}
})
</script>

我建议对对象使用响应式。

编辑:将响应应用于homePage反应对象。

最新更新