2017-01-17 145 views
2

我试图在Vue.js中实现Google Places自动完成功能。Google Places Autocomplete Vue.js

API states that的​​3210类第一接受一个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 
+0

使用[ref](https://vuejs.org/v2/api/#ref) –

+0

@MathewJibin谢谢。 – softcode

回答

3

好了,所以下面的马修积斌的建议,使用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()

+0

这似乎得到了围绕输入字段的div,而不是输入本身。 – Henry

相关问题