Vue2-Google-Maps 使用 beforeEnter() Route Guard 访问 gmapApi

Vue2-Google-Maps Accessing gmapApi using beforeEnter() Route Guard

上下文: 我正在尝试通过 beforeEnter() 路线守卫上的 place_id 获取地点数据。本质上,我希望当有人准确输入 url 时加载数据 www.example.com/place/{place_id}。目前,当我使用我的自动完成输入然后输入路线时,一切都可以直接工作,但是当我从新选项卡直接访问 url 时,它不起作用。我认为问题是因为尚未创建 google

问题:如何使用beforeEnter()路由守卫访问PlacesService()

错误: Uncaught (in promise) ReferenceError: google is not defined

示例代码: 在我的商店模块之一中:

const module = {
  state: {
    selectedPlace: {}
  },
  actions: {
    fetchPlace ({ commit }, params) {
      return new Promise((resolve) => {
        let request = {
          placeId: params,
          fields: ['name', 'rating', 'formatted_phone_number', 'geometry', 'place_id', 'website', 'review', 'user_ratings_total', 'photo', 'vicinity', 'price_level']
        }
        let service = new google.maps.places.PlacesService(document.createElement('div'))
        service.getDetails(request, function (place, status) {
          if (status === 'OK') {
            commit('SET_SELECTION', place)
            resolve()
          }
        })
      })
    },
  },
  mutations: {
    SET_SELECTION: (state, selection) => {
      state.selectedPlace = selection
    }
  }
}

export default module

在我的 store.js:

import Vue from 'vue'
import Vuex from 'vuex'
import placeModule from './modules/place-module'
import * as VueGoogleMaps from 'vue2-google-maps'

Vue.use(Vuex)

// gmaps
Vue.use(VueGoogleMaps, {
  load: {
    key: process.env.VUE_APP_GMAP_KEY,
    libraries: 'geometry,drawing,places'
  }
})

export default new Vuex.Store({
  modules: {
    placeModule: placeModule
  }
})

在我的路由器中:

import store from '../state/store'

export default [
  {
    path: '/',
    name: 'Home',
    components: {
      default: () => import('@/components/Home/HomeDefault.vue')
    }
  },
  {
    path: '/place/:id',
    name: 'PlaceProfile',
    components: {
      default: () => import('@/components/PlaceProfile/PlaceProfileDefault.vue')
    },
    beforeEnter (to, from, next) {
      store.dispatch('fetchPlace', to.params.id).then(() => {
        if (store.state.placeModule.selectedPlace === undefined) {
          next({ name: 'NotFound' })
        } else {
          next()
        }
      })
    }
  }
]

我试过的: - 将 new google.maps.places.PlacesService 更改为 new window.new google.maps.places.PlacesService - 使用 beforeRouteEnter() 而不是 beforeEnter() 作为导航守卫 - 将 google.maps... 更改为 gmapApi.google.maps...gmapApi.maps... - 向深渊尖叫 - 质疑我做过的每一个决定

编辑: 我也尝试了维基 here

中提出的 this.$gmapApiPromiseLazy()

该插件仅向 Vue 实例(组件)添加了一个提供 this.$gmapApiPromiseLazy 的 mixin,但你很幸运......它还向 Vue 静态添加了相同的方法

Source code

Vue.mixin({
  created () {
    this.$gmapApiPromiseLazy = gmapApiPromiseLazy
  }
})

Vue.$gmapApiPromiseLazy = gmapApiPromiseLazy

所以您在商店或路由器中需要做的就是使用

import Vue from 'vue'

// snip...

Vue.$gmapApiPromiseLazy().then(() => {
  let service = new google.maps.places....
})