如何将异步变量传递到Vue插件(VueGoogleMaps)中的选项



在我的应用程序中像一样使用包"vue2谷歌地图"之前

// app.js 
import apiKey from './apiKeyGoogleMap';
import * as VueGoogleMaps from "vue2-google-maps";
Vue.use(VueGoogleMaps, {
load: {
key: apiKey, //google map api key, load from apiKeyGoogleMap.js
libraries: "places"
}
});
new Vue({
el: '#app',
i18n,
template: '<app/>',
// Register App Component
components: {
app: App,
...
}
});
// apiKeyGoogleMap.js
const apiKeyGoogleMap = '';
export default apiKeyGoogleMap;

现在,如何从API加载变量apiKey,而不是从apiKeyGoogleMap.js加载?

// app.js
import * as VueGoogleMaps from "vue2-google-maps";
Vue.use(VueGoogleMaps, {
load: {
key: apiKey, // I want to load this variable from API 
libraries: "places"
}
});

您可以推迟添加插件,直到数据加载完毕,但也应该推迟创建根Vue实例。

例如

import * as VueGoogleMaps from "vue2-google-maps";
fetch("/api")
.then(res => res.json())
.then(data => {
Vue.use(VueGoogleMaps, {
load: {
key: data.apiKey,
libraries: "places"
}
})
new Vue({
// router, store, render, etc
}).$mount("#app")
})

这与Phil的答案相同,但使用了async/await函数。(我很慢,但既然我已经走了这么远,我还不如把它贴出来。(

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios' // Or fetch or similar.
import * as VueGoogleMaps from "vue2-google-maps";
async function run () {
// This placeholder api does not have an apiKey of course.
const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1'
const apiResponse = await axios.get(apiUrl)
const { apiKey } = apiResponse.data 
Vue.use(VueGoogleMaps, {
load: {
key: apiKey,
libraries: "places"
}
})
new Vue({
render: h => h(App)
}).$mount('#app')
}
run()

如果你不想在安装应用程序之前等待请求,那么你可以在组件内部执行同样的操作,并删除Vue.use((,这只是为了使插件全局化。(例如:https://dev.to/terrierscript/example-for-google-map-with-vuejs-without-vue-library--3gf5)

最新更新