Can you please provide guidance on how to dynamically add number values from an array to a select tag in Vue.js?

I'm trying to populate a select tag with options from an array variable that contains arrays of number values. However, the values being output appear to be blank.

Here is the HTML code:

  <select required id="dropDown">
    <option>Select here</option>
    <option v-for="choice in choices">{{ choice }}</option>
  </select>

And here is the Javascript code:

var vm = new Vue({   
el: 'body',    
data:{
    'choices': [1,2,3,4,5]
    }
});

Could anyone kindly point out where I may have gone wrong? I am new to this and would appreciate any guidance or advice you can provide.

Answer №1

To make Vue work correctly, ensure that the el option contains a valid DOM element for mounting. You have specified 'body' as the selector, so Vue will attempt to mount on the body element.

Your code is accurate otherwise. Just enclose your HTML within body tags and everything should function properly!

var vm = new Vue({   
  el: 'body',    
  data:{
    'choices': [1,2,3,4,5]
  }
});
<!-- Load Vue JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>

<!-- Ensure the presence of body tags so that `el: 'body'` points to a valid HTML element -->
<body>
  <select required id="dropDown">
    <option>Select here</option>
    <option v-for="choice in choices">{{ choice }}</option>
  </select>
</body>

Answer №2

When retrieving data from the backend, it's important to approach it differently. Let's say you have a list of categories that is being fetched from the backend.

 <el-select
              v-model="categorySelect.selected"
              size="large"
              name="category_id"
              single
              v-bind:placeholder="$t('products.category')"
          >
            <el-option
                v-for="item in categorySelect.autocompleteItems"
                :key="item.id"
                :label="item.name_en"
                :value="item.id"
            ></el-option>
          </el-select>

Your code structure should resemble this :

categorySelect: {
    selected: [],
    autocompleteItems: this.categoriesItem,
  },

categoriesItem: {
      required: false,
      type: Object
    },

Afterwards, fetch your data within your view like so :

:categories-item="{{$categories}}"

In the provided example above, you can populate your select list with distinct data originating from the backend.

Happy Coding!

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

Exploring nested maps in JavaScript

I attempted to nest a map within another map and encountered an issue where the innermost map is being executed multiple times due to the outer map. The goal is to link each description to a corresponding URL (using # as placeholders for some links). Here ...

Dynamic and operational icons accompany the AngularJS search input field

Currently, I am delving into the world of AngularJS and experimenting with a search box. Within this search box, I want to incorporate three icons: a magnifying glass, a cross, and a spinner. For the first scenario, I envision the magnifying glass appearin ...

Performing a NodeJS MySQL query using chain promises

I have a set of 3 functions that I need to call step by step. For example, after calling the first function and getting a result, I must then call the second function and pass the parameter returned from the first call. Once the second call is completed, I ...

Locating consecutive combinations of characters in a two-dimensional array using Java

I am on a quest to search for a specific combination of char letters within a large 2D array filled with random letters from the alphabet, ranging from 'a' to 'z'. The combination that I am seeking is quite specific - it consists of the ...

What is the best way to manage several asynchronous requests concurrently?

Can anyone recommend some valuable resources or books that explain how to effectively manage multiple asynchronous requests? Consider the code snippet below: Payment.createToken = function(data) { var data = data; apiCall("POST", "api/createToke ...

Incorporating a loading animation with an AJAX call

I've come across various solutions to this issue, one of the most enlightening being a response on Stack Overflow suggesting to "display it as soon as you initiate the AJAX call" and then "hide the image once the request is complete." But how would I ...

Tic-Tac-Toe: The square's value stays unchangeable

Currently, I am working on creating a tic-tac-toe game using pure vanilla Javascript, so I am aiming to keep it as simple as possible. I have run into an issue and need some guidance. The main requirement is that once a square has been clicked and filled ...

Click on a row in ReactTable to toggle the background color or expand the row

Is there a way to toggle the row background color in ReactTable when it is expanded? I have tried using onExpandedChange but haven't had any success. Any suggestions on how to achieve this would be greatly appreciated. Thank you! https://i.sstatic.ne ...

Trouble with formatting a HTML form

I have been working on dynamically creating HTML forms using a function called makeInput(). However, I am facing an issue where the text input boxes are appearing next to each other when I click the "Add Course" button, instead of one per line. Below is ...

Setting up Stylelint in a Next.js project: A step-by-step guide

I'm looking to incorporate Stylelint into my Next.js app. Can I modify the next.config.js file to include the stylelint-webpack-plugin, in order to receive style errors during compilation? // next.config.js module.exports = { reactStrictMode: true, ...

Unexpected Issues with the Ant Design Sidebar Layout Demo

My React webapp is utilizing the Ant design component framework version 4. I attempted to integrate this example from the Antd documentation into my webapp: https://codesandbox.io/s/ymspt However, when I implemented the code in my webapp, the result didn ...

The flow of events is not hindered by an if statement, even when the code within it is executed

I'm facing an issue where the console.log statement keeps executing even after calling the search function within the "if statements" in my code. Is there a way to prevent this from happening? function search() { /** * The Tweet checking algori ...

What is the best way to tally data-ids within an anchor tag using jQuery or plain JavaScript?

find total number of data-id attributes within tag a I am looking for a way to calculate the count of my id attribute, whether it is in data-id or another form, using JavaScript. Edit ...

What is the best approach for overlaying random meshes onto a terrain using a heightmap in three.js?

I'm interested in plotting randomly generated meshes at the y-position that corresponds to the terrain's height in three.js. While browsing through the documentation, I came across the raycaster method, which seems like it could be useful. Howeve ...

Rotating Images in 3D with CSS

I am looking for guidance on how to create a rotating image effect on a webpage using CSS/JS. The image should rotate into the plane of the page, similar to the example shown in this post. Can you assist me with this? To better illustrate what I'm tr ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

What is an alternative way to retrieve the page title when the document.title is unavailable?

Is there a way to retrieve the page title when document.title is not available? The code below seems to be the alternative: <title ng-bind="page.title()" class="ng-binding"></title> How can I use JavaScript to obtain the page title? ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...

The Cloudinary setup does not retrieve information from the .env file

I am currently integrating Cloudinary with my node.js project... Unfortunately, I have encountered an issue where cloudinary.config is not able to read data from the .env file. Instead, I am required to input them directly into the code! const cloudinary ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...