我使用 google places-api 來獲取一個或一個地點串列。對于地點串列中的每個地點,我想獲得額外的資料(例如網站)——這是從另一個 api(地點詳細資訊)完成的。
問題是我可以在 google 控制臺中看到所有資料,但在 DOM 中看不到 - 只有第一個 API 中的資料可見({{item.website}}屬性為空)
這是我的代碼:
<input type="text" id="searchPlace" v-on:keyup.enter="getPlaces()" placeholder="Type a name, address etc..." v-model="placeToSearch">
<div v-for="(item, key) in objPlaces" :key="key">
{{ item.name }} | {{item.place_id}} | {{item.rating}} | {{item.website}}
</div>
<script>
var myObject = new Vue({
el: "#app",
data: {
placeToSearch: "",
objPlaces: null,
},
methods: {
getPlaces() {
let places = null;
axios
.get('@Url.Action("GetPlace")', { params: { name: this.placeToSearch }})
.then((res) => {
places = res.data.results;
})
.finally(() => {
// iterate each place to get its website
places.forEach(function (el) {
axios
.get('@Url.Action("GetPlaceDetails")',{params: { placeId: el.place_id }})
.then((res) => {
el["website"] = res.data.result.website;
});
this.objPlaces = places;
console.log(this.objPlaces); // all the data is displayed
});
});
},
},
- 請注意我正在使用服務器端從 google api 獲取詳細資訊
uj5u.com熱心網友回復:
您可能會發現使用async/await而不是回呼函式更容易。
const myObject = new Vue({
el: "#app",
data() {
return {
placeToSearch: "",
objPlaces: null,
}
},
methods: {
async getPlaces() {
const res = await axios.get('@Url.Action("GetPlace")', {
params: { name: this.placeToSearch },
});
const places = res.data.results;
this.objPlaces = places.map(async (el) => {
const res = await axios.get('@Url.Action("GetPlaceDetails")', {
params: { placeId: el.place_id },
});
el.website = res.data.results.website;
return el;
});
},
},
});
注 1:我還沒有測驗過這個,但總體思路就在那里。
注 2:缺少try/catch以處理來自 API 的錯誤。
uj5u.com熱心網友回復:
您缺少 data 函式中的 return 陳述句。data 選項應該始終是回傳新物件的組件背景關系中的函式。
data(){
return {
placeToSearch: "",
objPlaces: null,
}
}
您可以從檔案中閱讀更多相關資訊:https : //vuejs.org/v2/guide/components.html#data-Must-Be-a-Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401282.html
標籤:Vue.js
上一篇:自定義vuetify變數-為什么@import必須在variables.scss檔案的末尾?
下一篇:在vuejs3中截斷單詞(字符)
