Quiero devolver la matriz de headings de una función axios.get y usarla en el root level dentro de mi vue component pero cuando intento devolverla, muestra:
ReferenceError: headings is not defined Este es el script element de mi 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>Editar:
Gracias a Thomas y huan feng puedo hacer esto:
<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> Esta es la solución más elegante porque los objetos reactive proporcionan el marco más limpio cuando se trabaja con arreglos. Llámalo desde el vue component así:
<h2>{{ state.headings.en }}</h2> Dado que axios es asynchronous devolver la variable al root level es más difícil y, en mi caso, no es necesario. Puedo sacarlo adentro 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);Ampliando mi comentario:
<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>Y sugiero usar reactivos para objetos.
EDITAR: aplicar la respuesta al homePage reactivo de la página de inicio.