Google Places自动完成Vue.js [英] Google Places Autocomplete Vue.js

查看:66
本文介绍了Google Places自动完成Vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Vue.js中实现Google地方信息自动填充功能.

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

API指出 自动完成类首先使用一个 inputField:HTMLInputElement ,如其示例中所使用的:

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']});

由于我们无法在Vue.js中通过元素的ID传递元素?这将如何实现?我们将通过什么样的结构?

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?

例如以下代码失败

<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 ,我明白了.还有很多事情要做,但克服了最初的障碍.

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>

文档中的另一项内容:

关于裁判注册时间的重要说明:因为裁判本身是通过render函数创建的,您不能在初始渲染中访问它们-它们尚不存在!

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()钩子不是正确的钩子.我们正在寻找 mount().

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

这篇关于Google Places自动完成Vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆