使用VueJs选择位置后,重置Google自动完成输入值

时间:2019-03-27 14:48:36

标签: google-maps vue.js

选择位置后,我需要清理Google自动完成输入。我为组件的值属性分配了一个数据值,但似乎没有改变。即使使用手表,似乎也没有任何反应。

这是我的InputPlace组件:

<template>
  <label class="form-label-place" for="city">
    <input class="form-control pr-5" :value="value" type="text" id="inputPlace" name="city" placeholder="Ingresa tu ciudad">
  </label>
</template>
<script>
export default {
  name: 'input-place',
  props: {
    value: ''
  },
  mounted() {
      // Google autocomplete
      const options = {
        types: ['(cities)'],
        componentRestrictions: {country: "PE"}
      };

      const places = new google.maps.places.Autocomplete(document.getElementById('inputPlace'), options);
      google.maps.event.addListener(places, 'place_changed', () => {
        this.$parent.placeChanged(places)
      });
  }
}
</script>

这就是我在视图中使用它的方式:

<template>
  ...
  <input-place :value="InputPlaceValue"></input-place>
</template>
<script>
  ...
  data() {
    return {
      activePlaces: [],
      InputPlaceValue: ''
    }
  },
  methods: {
    placeChanged(places) {
       let placeName = places.getPlace().name;

       if(!this.activePlaces.includes(placeName)) this.activePlaces.push(placeName)
       this.InputPlaceValue = ''
    }
  }
</script>

希望可以帮助我,谢谢。

1 个答案:

答案 0 :(得分:1)

清除自动填充文本字段的一种方法是:

a)使用v-model指令

<input v-model="selectedAddress" class="form-control pr-5" type="text" id="inputPlace" name="city" placeholder="Ingresa tu ciudad">

b)并在触发以下place_changed事件后清除输入值:

google.maps.event.addListener(places, "place_changed", () => {
  this.selectedAddress = "";
});

InputPlace.vue示例

<template>
  <label class="form-label-place" for="city">
    <input class="form-control" type="text" id="inputPlace" v-model="selectedAddress" name="city" placeholder="Search..">
  </label>
</template>
<script>
export default {
  /* global google */
  name: "input-place",
  data () {
    return {
      selectedAddress: ''
    }
  },
  mounted() {
    const options = {
      types: ["(cities)"]
    };
    const places = new google.maps.places.Autocomplete(
      document.getElementById("inputPlace"),
      options
    );
    google.maps.event.addListener(places, "place_changed", () => {
      this.selectedAddress = "";
      this.$parent.placeChanged(places)
    });
  }
};
</script>