A Select Element’s Binding to an Object

Make a VueJS project

Use the command line to create a Vue.js project:

vue create demo

Now launch Visual Studio Code and open the just created project.

Installation

Now run the following command to add Bootstrap to this project.

npm install bootstrap

Go ahead and add the following code to the main.js file.

import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.css';
createApp(App).mount('#app')

Open App.vue now and insert the following code.

<template class="mt-5 pt-5">
   <div class="main_container">
    <div class="main text-center">
    <h4 class="mb-3">Binding vue js Select Element to Object Example</h4>
    <select v-model="chosenObj" class="form-control pe-5" >
      <option v-for="item in Data" :key="item">
        {{ item.name }}
      </option>
    </select>
    <h5 class="d-flex mt-4">
      {{ chosenObj | json }}
    </h5>
  </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      chosenObj: '',
      id: '',
      name:'',
      Data : [
    { id: 'one', name: 'Manasvi' },
    { id: 'two', name: 'Prinkesha' },
    { id: 'three', name: 'Asmita' },
    { id: 'four', name: 'Krishna' },
    { id: 'four', name: 'Rajvi' },
  ],
    }
  }
}
</script>

<style>
.main_container{
  width: 30%;
  margin: 0 auto ;
}
</style>

Run the project now by using the aforementioned command.

npm run serve

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories