I need to fetch the headings
array from an axios.get
call and utilize it at the root level
within my Vue component
. However, when I attempt to return it, I encounter this error:
ReferenceError: headings is not defined
Here is the script element
in my 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>
Edit:
Credit goes to Thomas and huan feng for helping me arrive at this solution:
<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>
This approach is considered the most elegant because reactive
objects offer a cleaner structure when working with arrays. Use it in the Vue component
like this:
<h2>{{ state.headings.en }}</h2>
Due to the asynchronous
nature of axios
, retrieving the variable at the root level
proves to be more challenging and unnecessary in my scenario. Displaying it within the then
block suffices.