我想headings從axios.get函式回傳陣列并root level在我的內部使用它,vue component但是當我嘗試回傳它時,它顯示:
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>
編輯:
感謝Thomas和huan 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>
由于axios在asynchronous回傳變數到root level是比較困難的,在我的情況下,沒有必要的。我可以在里面輸出它then。
uj5u.com熱心網友回復:
// 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);
uj5u.com熱心網友回復:
擴展我的評論:
<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反應物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338439.html
標籤:javascript Vue.js 公理 Vuejs3
