[英]VueJS 3 / Vuex - How to display data from a nested json result
親愛的,
我已經為此苦苦掙扎了幾個小時,甚至遵循了基礎教程。
我試圖在我的 Vue 3 項目中顯示 Json 中的一些數據,當數據在數組中時,使用循環我得到我需要的一切,但如果它不在數組中,我會收到錯誤或數據粘在一起。
我創建了一個這樣的 vuex 商店:
const region = {
state: {
region: {}
},
mutations: {
SET_REGION(state, region) {
state.region = region
}
},
actions: {
getAllRegions({ commit }) {
axios.get("/api/regions/get")
.then(response => {
commit('SET_REGION', response.data)
})
}
},
getters: {
getAllRegions (state) {
return state.region
},
getDelegue (state) {
return state.region.delegue
}
}
};
當我在頁面中調用此數據時,我得到以下結果:
[
{
id: 3,
name: "Occitanie",
agents: [ ],
delegue: null
},
{
id: 2,
name: "Ile de France",
agents: [ ],
delegue: null
},
{
id: 4,
name: "Hauts de France",
agents: [ ],
delegue: null
},
{
id: 1,
name: "Grand Est",
agents: [
{
lastname: "DOE",
firstname: "John",
phone: "+331234567890",
user: {
email: "b@b.b"
}
}
],
delegue: {
lastname: "DURSLEY",
firstname: "Jake",
phone: "+3309987654321",
user: {
email: "a@a.a"
}
}
}
]
結果對我來說似乎不錯。 現在在我的 Vue 中,我想顯示數據,這是我在“DELEGUE”數據方面遇到麻煩的地方。
<div v-for="region in myFunctionToRetrieveJsonData">
<p>Name: {{ region.name }}</p> // WORKING
<p v-for="agent in region.agents">
{{ agent.lastname + ' ' + agent.firstname }}<br> // WORKING
{{ agent.phone }}<br> // WORKING
<span v-for="email in agent.user">{{ email }}</span> // WORKING
// THIS WAY
Delegue: {{ agent.delegue.lastname + ' ' + agent.delegue.firstname }} // NOT WORKING
// ALSO THIS WAY
Delegue: {{ agent.delegue[0].lastname + ' ' + agent.delegue[0].firstname }} // NOT WORKING
// THE OTHER WAY
<p v-for="delegue in region.delegue">
Delegue: {{ delegue }} // DISPLAY: DURSLEYJake+3309987654321{"email":"a@a.a"} NOT GOOD
</p>
</p>
</div>
我收到此錯誤: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'lastname')
所以我知道對於 USERS 我可以做一個 v-for 循環,但是在 DELEGUE 的情況下,我不能馬上訪問,或者如果我做一個循環,我有所有的數據沒有分開,我可以'不要用它工作。
你們有什么想法嗎?
非常感謝您的幫助。
洛根
如果我理解正確,請看下面的代碼片段:
new Vue({ el: '#demo', data() { return { items: [ {id: 3, name: "Occitanie", agents: [ ], delegue: null}, {id: 2, name: "Ile de France", agents: [ ], delegue: null}, {id: 4, name: "Hauts de France", agents: [ ], delegue: null}, {id: 1, name: "Grand Est", agents: [{lastname: "DOE", firstname: "John", phone: "+331234567890", user: {email: "b@bb"}}], delegue: {lastname: "DURSLEY", firstname: "Jake", phone: "+3309987654321", user: {email: "a@aa"}}} ] } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="demo"> <div v-for="region in items"> <p>Name: {{ region.name }}</p> <p v-for="agent in region.agents"> {{ agent.lastname + ' ' + agent.firstname }}<br> {{ agent.phone }}<br> <span v-for="email in agent.user">{{ email }}</span> Delegue: {{region.delegue?.lastname + ' ' + region.delegue?.firstname }} </p> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.