I want to return the headings
array from an axios.get
function and use it on root level
inside my vue component
but when I try to return it, it shows:
JavaScript
x
2
1
ReferenceError: headings is not defined
2
This is the script element
from my Vue3 Component
:
JavaScript
1
24
24
1
<script setup>
2
import {ref} from 'vue';
3
4
const homePage = ref({
5
heading: "",
6
content: "",
7
image: ""
8
});
9
10
axios.get('/home')
11
.then(res => {
12
const data = res.data[res.data.length - 1]
13
const headings = {
14
en: data['heading_(en)'],
15
de: data['heading_(de)'],
16
ar: data['heading_(ar)'],
17
}
18
return headings;
19
})
20
21
console.log(headings);
22
23
</script>
24
Edit:
Thanks to Thomas and huan feng I can do this:
JavaScript
1
24
24
1
<script setup>
2
import {reactive} from 'vue';
3
4
const state = reactive({
5
headings: {},
6
content: {},
7
image: ""
8
})
9
10
axios.get('/home')
11
.then(res => {
12
const data = res.data[res.data.length - 1]
13
14
state.headings = {
15
en: data['heading_(en)'],
16
de: data['heading_(de)'],
17
ar: data['heading_(ar)'],
18
}
19
20
console.log(state.headings.en)
21
})
22
23
</script>
24
This is the most elegant solution because reactive
objects provide the cleanest framework when working with arrays. Call it from the vue component
like so:
JavaScript
1
2
1
<h2>{{ state.headings.en }}</h2>
2
Since axios
is asynchronous
returning the variable into root level
is more difficult and in my case not necessary. I can output it inside then
.
Advertisement
Answer
JavaScript
1
18
18
1
// Better to wrap page states in a reactive object
2
const state = reactive({
3
headings: []
4
})
5
6
axios.get('/home')
7
.then(res => {
8
const data = res.data[res.data.length - 1]
9
state.headings = {
10
en: data['heading_(en)'],
11
de: data['heading_(de)'],
12
ar: data['heading_(ar)'],
13
};
14
})
15
// Use state.headings before this line,
16
// Unpack it and you can directly use headings in template
17
const {headings} = toRefs(state);
18