Google Places Autocomplete Vue.js

白昼怎懂夜的黑 提交于 2019-12-12 18:49:37

问题


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.



来源:https://stackoverflow.com/questions/41688977/google-places-autocomplete-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!