Google 地点自动完成 Vue.js

Google Places Autocomplete Vue.js

我正在尝试在 Vue.js 中实现 Google 地点自动完成功能。

API states that Autocomplete class 首先取一个 inputField:HTMLInputElement,如他们的示例中所用:

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

既然我们不能通过元素的 ID 在 Vue.js 中传递元素?这将如何实现,我们将通过什么样的构造?

例如以下代码失败

<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>

错误:

InvalidValueError: not an instance of HTMLInputElement

好的,所以按照 Matthew Jibin 关于使用 ref 的建议,我让它出现了。还有很多事情要做,但要克服最初的障碍。

<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>

另外一个,来自文档:

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!

所以 created() 挂钩不正确。 mounted() 就是我们要找的。