dpm24
dpm24

Reputation: 35

How to acced to google object in vue 2?

I'm trying to use the google maps API at my vue2 project and I have tried some ways that have failed. After using the vue2googlemaps module and the node module from google I have decided to use the CDN directly and add it to the index page. My problem now is that to acced to the google object, for example, to create a Marker or something like that, I need to use this.marker = new window.google.maps.Marker() for example, but in the tutorials I have seen, everyone uses directly the google object and never uses that window. I can`t understand why it happens. It would be appreciated if someone shows me the correct way to import or use this library on google.

Upvotes: 0

Views: 774

Answers (1)

tao
tao

Reputation: 90013

It's because your template's code is compiled and executed in your component instance (a.k.a vm) 's scope, not in the global (a.k.a. window) scope.

To use google directly in your template you could add the following computed:

computed: {
  google: () => window.google
}

If your problem is not having google defined in the component's <script>, a simple solution is to add it as a const at the top:

import Vue from 'vue';
const google = window.google;

export default Vue.extend({
  computed: {
    google: () => google // also make it available in template, as `google`
  }
})

An even more elegant solution is to teach webpack to get google from the window object whenever it's imported in any of your components:

vue.config.js:

module.exports = {
  configureWebpack: {
    externals: {
      google: 'window.google'
    }
  }
}

This creates a google namespace in your webpack configuration so you can import from it in any of your components:

import google from 'google';

//... 
  computed: {
    google: () => google // provide it to template, as `google`
  }

Why do I say it's more elegant?
Because it decouples the component from the context and now you don't need to modify the component when used in different contexts (i.e: in a testing environment, which might not even use a browser, so it might not have a window object, but a global instead; all you'd have to do in this case is to define a google namespace in that environment and that's where your component will get its google object from; but you wouldn't have to tweak or mock any of the component's methods/properties).

Upvotes: 1

Related Questions