N
N
nastya_zholudeva2018-03-21 11:22:16
Vue.js
nastya_zholudeva, 2018-03-21 11:22:16

How to make the autocomplete component more generic?

<template>
<div>
  <p>Try typing <em>draw</em> or <em>fill</em></p>
  <input id="autocomplete" type="text"
    :value="value"
    @input = "updateValue($event.target.value)"
    @blur = "updateValue()"
  />
  <div id="autocomplete_result" v-show="open">
    <p v-for="(item, index) in values"
       :key="item.id"
       @click="select(index)"
    >
      <img :src="item.img" alt="">
      <span>{{ item.title }}</span>
      <span v-if="desc">{{ item.desc }}</span>
    </p>
  </div>
</div>
</template>

<script>
export default {
  name: 'Autocomplete',
  props: {
    value: {
      type: String,
      default: ''
    },
    getItems: {
      type: Function
    },
    desc: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      open: false,
      values: []
    }
  },
  methods: {
    updateValue (value) {
      this.open = true
      this.getItems().then(result => {
        this.values = result
      })
      this.$emit('input', value)
    },

    select (index) {
      this.$emit('input', this.values[index].title + ' ' + this.values[index].desc)
      this.open = false
    }
  }
}
</script>

now, when the desired element is selected, this.$emit('input', this.values[index].title + ' ' + this.values[index].desc) is emitted to the input, but, let's say, the description is not needed on another page. How to make it so that only the necessary properties of the data object are emitted?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2018-03-21
@nastya_zholudeva

1. Pass an array of required keys in props and filter the response
2. Emit this.values[index] and don't worry

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question