Algolia vue-places:选择后清除输入

Algolia vue-places: Clear input after selection

我正在使用 vue-places 组件在 Vue 中呈现 Algolia 放置搜索输入 - 它工作得非常好。

在用户从搜索下拉列表中选择/接受建议后,我想清除输入并允许他们再次搜索。根据提供的标准示例,我尝试在更改处理程序中将 form.country.label v-model 值设置回 null:

<template>
  <places
    v-model="form.country.label"
    placeholder="Where are we going ?"
    @change="selectLocation"
    :options="options">
  </places>
</template>

<script>
import Places from 'vue-places';

export default {
  data() {
    return {
      options: {
        appId: <YOUR_PLACES_APP_ID>,
        apiKey: <YOUR_PLACES_API_KEY>,
        countries: ['US'],
      },
      form: {
        country: {
          label: null,
          data: {},
        },
      },
    };
  },
  components: {
    Places,
  },
    methods: {
      selectLocation: function(event: any) {
        if (event.name !== undefined) {
          /**
           * implementation not important
           */

          this.form.country.label = null;
        }
      }
    }
}
</script>

selectLocation 方法按预期触发 - 但我找不到任何方法将输入值设置为空。

如何从组件方法更新数据值并将其反映在引用组件中 - 在本例中是 Algolia 放置输入?

问题的发生是因为 vue-places 如何代理来自底层实现的 change 事件。当接收到 change 事件时,它广播相同的事件 然后更新输入值:

Places.vue:

this.placesAutocomplete.on('change', (e) => {
  this.$emit('change', e.suggestion);
  this.updateValue(e.suggestion.value);
});

这意味着任何在我们的更改处理程序中设置值的尝试都将立即被覆盖。

我的解决方案是创建一个refvue-places实例然后使用built-inVue.nextTick使用内部places.jssetVal 方法 调用 updateValue:

之后
    methods: {
      selectLocation: function(event: any) {
        if (event.name !== undefined) {
          // do something with the value

          Vue.nextTick(() => {
            // clear the input value on the next update
            this.$refs.placesSearch.placesAutocomplete.setVal(null);
          });
        }
      }
    }