【问题标题】:Algolia vue-places: Clear input after selectionAlgolia vue-places:选择后清除输入
【发布时间】:2020-10-16 21:21:27
【问题描述】:

我正在使用 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 放置输入?

【问题讨论】:

    标签: javascript vue.js vue-component vuex algolia


    【解决方案1】:

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

    Places.vue:

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

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

    我的解决方案是为vue-places 实例创建一个ref,然后使用内置的Vue.nextTick 来使用内部的places.js setVal 方法调用之后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);
              });
            }
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2021-11-22
      • 2017-02-08
      • 2021-10-11
      • 2018-09-11
      • 1970-01-01
      • 2021-07-05
      • 2018-06-13
      • 1970-01-01
      相关资源
      最近更新 更多