How to dynamically generate <select> <option> elements in VueJS using the v-for directive

Just started exploring VueJS and I recently learned how to use a v-for loop to populate a Select Options box.

<select>
    <option v-for="person in persons" :value="personid">{{ personname }}</option>
</select>

Below is the list I am working with.

"persons": {
        "2": "Person1",
        "3": "Person2",
        "4": "Person3"
    }

This is the desired outcome for the Select Options box.

<select id="persons">
    <option value="3">Person1</option>
    <option value="4">Person2</option>
</select>

Answer №1

Fortunately, Vue has the capability to iterate through the properties of an Object as detailed in v-for with an Object.

Below is a code snippet that can assist you in achieving your desired outcome.

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  data: () => {
    return {
      persons: {
        "2": "Person1",
        "3": "Person2",
        "4": "Person3"
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select id="persons">
    <option v-for="(name, id) in persons" :value="id">{{name}}</option>
  </select>
</div>

Answer №2

You're almost there, just make a few tweaks to that selection:

<select id="people" >
  <option
    v-for="(item, index) in peopleArray"
    :value="index"
    :key="index"
  >{{ item }}</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating Rails Active Storage in a VueJS Blog

Utilizing Active Storage in a Rails 5.2 application with AWS S3 for image hosting has been successful when using <%= image_tag @gin.pic %> in an HTML view. However, I am encountering difficulties with the file path while integrating a separate VueJS ...

The logo image dynamically switches as the user scrolls through various colored sections

Looking to create a feature that changes the logo image as users scroll through different colored sections. Specifically, switching between dark and light themes. a) How can we determine if the section the user is currently on has a dark or light theme? b ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Is it feasible to relocate an embedded swf file from one tag to another?

My HTML contains two containers for embedded swf files: <div id="player1"></div> <div id="player2"></div> If I load an embedded video into the first div (player1) like this: swfobject.embedSWF("someURL","player1"); Is it possibl ...

Creating a list of ranges in an array with the ADDRESS formula using Excel VBA

I need help populating a two-dimensional array of ranges with references to specific cells. I attempted to use the following pseudo code, but encountered syntax errors: Dim ArrayOfRanges() as Range ReDim ArrayOfRanges(10,1) For i = 1 to 10 Set A ...

Deploying Laravel and Vue.js on a shared hosting environment

My current project is built on Laravel and it has been deployed on a shared hosting server. Now, I am looking to integrate a Vue.js component into the existing setup. The issue I am facing is that during the deployment process, I neglected to install npm. ...

Adding text to an existing div element using jQuery and ensuring the div tag automatically adjusts its height according to the text length

I have attempted to implement the following code, but unfortunately, it is not functioning as expected. I am hopeful that someone can assist me. I am seeking a way for the div tag to dynamically increase its height based on the size of the text. Does any ...

Guide on setting a property for req.session

I'm a beginner in node.js and sessions, and I am having trouble setting properties to the session! I am trying to add a property to the session and save it in the database, but I keep getting errors. Here are my codes: app.js (main js file) const s ...

What steps should be taken to safely sanitize untrusted JSON data before parsing it with JSON.parse method

How can we properly sanitize a user-provided JSON string to prevent any vulnerabilities before executing JSON.parse(untrustedString)? My main concern revolves around prototype pollution, but I'm also interested in knowing about any other potential ri ...

Manipulating content with JavaScript in Internet Explorer using the outerHTML property is a powerful

Encountering an Issue with outerHTML in IE Browser If I try the following: txt = "Update Complete!"; msg = sub.appendChild(d.createElement("p")); msg.outerHTML = txt; It works without any problem. However, if I use: txt = "1 Error:<ul><li> ...

What is the best way to create a transparent sticky header that blends with the background while still maintaining visibility over images and text?

On my web page, the background features a radial gradient but the content extends beyond the viewport, causing the center of the gradient to not align with the center of the screen, producing the desired effect. However, I'm facing an issue with a sti ...

Conceal the <p> element when the user interacts with the internal href

After creating this document using JQuery, whenever the user clicks on different internal links, a div with id = "change" is loaded which effectively "erases" the content. My challenge at the moment is that while images are successfully deleted, text rema ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

Retrieving table information using javascript

My goal is to retrieve information from the <td> elements within the following HTML table: <table class="datadisplaytable" summary="This table lists the scheduled meeting times and assigned instructors for this class.."> <caption class="cap ...

How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to ...

Show the JSON data from the server in a table format

Is there a way to neatly display data received from an Ajax response within a table format? Below is the structure of the table: <table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table"> ...

Prevent automatic scrolling to the top of the page after submitting a form. Remain at the current position on the

After submitting a form, I want to prevent the page from automatically scrolling back up. How can I keep the same position on the page after form submission? <script type="text/javascript"> var frm = $('#form'); frm.submit(function ...

When an absolute positioned DIV is nested inside a relatively positioned DIV, it disappears when the page is scrolled

A unique feature of my DIV is that it remains fixed at the top of the page as you scroll. This is achieved by setting its position to fixed. However, within this main container, I have another div with a relative position. While the content in the relative ...

Leveraging Google maps to find nearby stores

I recently created a store locator but hit a roadblock when I discovered that Google Maps does not allow you to iframe the entire page. Is there a workaround for this issue to display the map? Or is there an alternative method that doesn't involve ifr ...

What is the best way to conceal a portion of the input value within a v-text-field?

The Challenge Ahead- This particular v-text-field has been created to enable users to manually input and modify their name on the website. However, for security reasons, I am looking to conceal all parts of the input value except the last character of the ...