gpt4 book ai didi

javascript - 如何从 Composition API 中的 Axios Response 返回变量到根级别?

转载 作者:行者123 更新时间:2023-12-04 17:09:54 26 4
gpt4 key购买 nike

我想退回 headings来自 axios.get 的数组函数并在 root level 上使用它在我的里面 vue component但是当我尝试返回时,它显示:

ReferenceError: headings is not defined

这是 script element来 self 的 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>

编辑:

感谢 Thomashuan feng 我可以做到这一点:

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

关于javascript - 如何从 Composition API 中的 Axios Response 返回变量到根级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69718499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com