Google Places Autocomplete Vue.js

2019-07-20 09:57发布

问题:

I am trying to implement Google Places Autocomplete in Vue.js.

The API states that the Autocomplete class first takes an inputField:HTMLInputElement, as used in their example:

autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
    {types: ['geocode']});

Since we cannot pass elements around by their ID's in Vue.js? How would this be achieved, and what kind of construct would we pass?

e.g. the following code fails

<template>
  <input id="autocomplete" placeholder="Enter your address" type="text"></input>
</template>

<script>
  export default {
    created() {
      var autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
    {types: ['geocode']});
    }
  }
</script>

with error:

InvalidValueError: not an instance of HTMLInputElement

回答1:

Ok so following Matthew Jibin's suggestion to use ref, I got it to show up. Lots more to do but initial hurdle overcome.

<template>
  <input ref="autocomplete" 
         placeholder="Enter your address" 
         type="text"
  />
</template>

<script>
  export default {
    mounted() {
      var autocomplete = new google.maps.places.Autocomplete(
      /** @type {!HTMLInputElement} */(this.$refs.autocomplete),
      {types: ['geocode']});
    }
  }
</script>

One addition, from the docs:

An important note about the ref registration timing: because the refs themselves are created as a result of the render function, you cannot access them on the initial render - they don’t exist yet!

So the created() hook isn't the right one. mounted() is what we're looking for.