0

I'm working on a small project using VueJS, I'm making an autocompletion, i would like to hide my dropdown list if the user click outside,

this is my code :

<template>
    <div class="autocomplete">
        <input autocomplete="off" type="text" class="form-control form-control-border"  v-bind:placeholder="this.placeholder" v-model="query" @keyup="autoComplete" @focus="suggestion = true" />
        <div v-if="data.length >= 1 && suggestion">
            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                <li @click="selected(item[label], item.id)" v-for="item in data" :key="item.id">
                    <a class="dropdown-item" href="#">{{ item[label] }}</a>
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
import {getAPI} from "../axios-api"

export default {
    props: {
        label: String,
        path: String,
        placeholder: String,
        action: String,
    },
    data() {
        return {
            suggestion: false,
            query: '',
            data: [],
        }
    },
    methods: {
        autoComplete(){
            if(/\S/.test(this.query) && this.query.length >= 3){
                getAPI.get(this.action + '?query=' + this.query).then((response) => {
                    this.data = response.data
                })
            }
        },
        selected(label, id){
            this.suggestion = false
            this.query = label
        }
    }
}
</script>

How can i detect outside click, so i can switch the value of suggestion to false again

Alice Munin
  • 511
  • 2
  • 13
  • 3
    I would suggest to use a directive for this. Something like this https://github.com/ndelvalle/v-click-outside should do the trick. – Jakub Michálek Apr 28 '21 at 14:12
  • Answer is extensively covered here https://stackoverflow.com/questions/36170425/detect-click-outside-element – Pierre_T Apr 28 '21 at 21:44

0 Answers0