Component Autocomplete Vuejs

Asked

Viewed 505 times

2

I want to create a component of autocomplete, then I have the following code.

<Input v-model="form.autocomplete.input" @on-keyup="autocomplete" />
<ul>
    <li @click="selected(item, $event)" v-for="item in form.autocomplete.res">
        {{item.title}}
    </li>
</ul>

autocomplete(e){
    const event = e.path[2].childNodes[4]

    if(this.form.autocomplete.input.length > 2){
        this.Base.get('http://localhost:3080/post/search/post', {
            params: {
                q: this.form.autocomplete.input
            }
        })
        .then(res => {
            this.form.autocomplete.res = res.data

            if(this.form.autocomplete.res.length > 0)
                event.style.display = 'block'
        })
    }
},
selected(item, e){
    this.form.autocomplete.item = item
    console.log(e)
}

However, how would I get the return after selecting my item in the main file?

Ex:

Home.vue

<Autocomplete :url="www.url.com/test" />

When selecting the item I want from mine autocomplete, how to pick up his return and store it in that file, as if I were using v-model?

NOTE: The URL and other information will pass via props subsequently.

  • You can explain this part better "how to take the return of it and store it in that file, as if I were using v-model" ?

  • 1

    @Felipeduarte In the example above my component, I store the return when selecting the list item on form.autocomplete.item, but this value is stored in autocomplete.vue and not in the file I’m using that in the case would be the Home.vue (or any other)

1 answer

1


I believe that the logic of the components leads to a pattern where the v-model will coupled the definition of the child component so that the same can capture it, treat it and even send again to the father, this can be done through the @input, example...

Vue.component('products-list', {
  template: '#my-input',
  data: function() {
    return{
        product : {
        	name: ""
        }
      }
    },
});

var app = new Vue({
  el: '#app',
  data: {
    product: {
      name: "",
    }
  }
});
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
  <products-list v-model="product.name"></products-list>
  <br>Componente pai : {{product.name}}
</div>

<template id="my-input">
  <div>
    <input @input="$emit('input',$event.target.value)"
    v-model="product.name"
    />
    <br><br>Componente filho : {{product.name}}
  </div>
</template>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.