我想从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>
由于axios
是asynchronous
,将变量返回到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
反应对象。