How to call events selected with the autocomplete in VueJS?
November 07, 2022Hi Friends đź‘‹,
Welcome To SortoutCode! ❤️
To add the autocomplete in vuejs. we are going to use the vuejs-auto-complete
package. We are going to see how to set up and how to use this package.
Today I am going to show you How you call events on selected with the autocomplete in VueJS?
Table of contains
- Setup the Vue.js
- Create FirstComponent.vue and import it into App.js
- Install the vuejs-auto-complete package
- Add autocomplete component to your app
Let’s start today’s tutorial How do I call events on selected with the autocomplete in VueJS?
Setup the Vue.js
First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, which will show you step by step process of installation.
How to Install the VueJS project?
Create FirstComponent.vue and import it into App.js
Create the new component in the src/components/
components folder. the component name is FirstComponent.vue
and imported into the App.js
file:
App.js
<template>
<div id="app">
<FirstComponent />
</div>
</template>
<script>
import FirstComponent from "./components/FirstComponent.vue";
export default {
name: "App",
components: {
FirstComponent,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Install the vuejs-auto-complete package
To install the vuejs-auto-complete
package into our app. we have to use the following command:
npm i vuejs-auto-complete
After the installation is complete, we have to add Autocomplete component to our app.
Add autocomplete component in our app
Let’s use the autocomplete component in our app. And also we are going to call the event after the value is selected from the autocomplete. Let’s see the code example:
<template>
<div style="width:800px; margin:0 auto;">
<h1>Welcome to sortoutcode.com</h1>
<autocomplete :source="color" @selected="showSelected">
</autocomplete>
<p>ID : {{ id }}</p>
<p>Name : {{ name }}</p>
</div>
</template>
<script>
import Autocomplete from 'vuejs-auto-complete'
export default {
name: "FirstComponent",
components: {
Autocomplete
},
data() {
return {
color: [{ id: 1, name: 'Red' },
{ id: 2, name: 'Green' },
{ id: 3, name: 'Yellow' },
{ id: 4, name: 'White' },
{ id: 5, name: 'Blue' }],
id: "",
name: "",
}
},
methods: {
showSelected(data) {
this.id = data.value;
this.name = data.display;
}
}
};
</script>
For now, let’s check the output.
All the best 👍.