sof*_*ode 2 javascript google-places-api vue.js
我正在尝试在Vue.js中实施Google地方信息自动填充功能.
该API规定的Autocomplete
类第一接受一个inputField:HTMLInputElement
,如在其实施例中使用:
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
Run Code Online (Sandbox Code Playgroud)
既然我们不能通过Vue.js中的ID传递元素?如何实现这一目标,以及我们将通过何种结构?
例如,以下代码失败
<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>
Run Code Online (Sandbox Code Playgroud)
有错误:
InvalidValueError: not an instance of HTMLInputElement
Run Code Online (Sandbox Code Playgroud)
好吧,按照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>
Run Code Online (Sandbox Code Playgroud)
一个补充,来自文档:
关于ref注册时间的一个重要注意事项:因为refs本身是由render函数创建的,所以你无法在初始渲染时访问它们 - 它们还不存在!
所以created()
钩子不是正确的.mounted()
是我们正在寻找的.