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

Establishing the primary meta properties on Vue Router

I've checked out the documentation here, and it appears that the meta property on the VueRouter object doesn't seem to have any effect (no description provided in the documentation)... Let's consider the following routes: let routes = [ ...

Automatically resize ui-select dropdown box to the left side

I've been tasked with incorporating AngularJS ui-select into my project, specifically creating a multiselect dropdown. Currently, the dropdown box automatically adjusts its width based on the length of the longest selectable text, causing it to extend ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

What is the scope parameter for the facebook-node-sdk in node.js?

https://github.com/amachang/facebook-node-sdk I decided to utilize this module in order to create a Facebook-integrated login for my node.js project, following the example provided with express: var express = require('express'); var Facebook = ...

The display message in Javascript after replacing a specific string with a variable

I'm currently working on a task that involves extracting numbers from a text input, specifically the first section after splitting it. To test this functionality, I want to display the result using an alert. The text input provided is expected to be ...

What could be causing the service worker in my Parcel.js-built PWA to function correctly when online but malfunction when offline?

Seeking Answers While my service worker functions flawlessly in installing and fetching files from the Cache Storage when online, it seems to lose its way once offline. Where could I be going wrong? I suspect it might be due to the loading order, incorre ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

The magic of $.ajax lies in its ability to load an unexpected URL, diverging from my original

Every time I send a request using an absolute URL, Ajax is posting the wrong URL. For instance, when I request "http://localhost/app/home/session", it mistakenly calls "http://localhost/app/home/home/session" var baseURL = function(link) { var url = & ...

Creating dynamic dropdown menus using JSON files in jQuery mobile is a useful technique for enhancing user experience on

I am working with a massive table (8 MBytes) that I need to filter using a small JavaScript application. The process works as follows: Countries Regions Skills I want the user to select one country, one region, and multiple skills as filters. Based on ...

What is the best way to implement the useCallback hook in Svelte?

When utilizing the useCallback hook in React, my code block appears like this. However, I am now looking to use the same function in Svelte but want to incorporate it within a useCallback hook. Are there any alternatives for achieving this in Svelte? con ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

How can I retrieve the line number of a code during runtime in JavaScript?

Is there a way to add a console.log statement that would indicate the line number it is on in JavaScript? For example: console.log ('Line:', [code to get the line]). The output in the console would be Line: [line number], helping me identify wher ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...

Where should data processing be conducted: in the service or controller layer?

Here's a question regarding the best practices for organizing code. I'm fetching data from an API using $resource and I need to manipulate it before displaying it on the view. My dilemma is at which stage should I process the data? My current b ...

Render a component in certain routes based on specific conditions in React

This is my Index.js ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router> <App className="app-main" /> </Router> </Provider> </R ...

Having trouble with radio button validation in JS?

I'm having difficulty understanding why the radio button is not staying checked when I select another option. To demonstrate, I created a fiddle where initially the "diy" button is selected but switching to "paid" causes the radio button to jump back ...

EdgeDriver with Selenium and Java can be interrupted by a modal window dialog box, causing the test script to pause its execution

I am in the process of creating a test script for our web application to test the upload functionality of a profile picture using Microsoft Edge and EdgeDriver. However, I am facing an issue where the script stops running completely after initiating the cl ...

Using PHP script, extract information from a JSON file and populate a dropdown menu in HTML

I am attempting to extract data from a JSON file using PHP and then display this data in an HTML select tag on the front end. Below is my PHP file: <?php ini_set('display-errors', 'on'); error_reporting(E_ALL); $executionStartTim ...

Is there a way to redirect links within an iframe when a user decides to open them in a new tab?

I am currently developing a web application that allows users to access multiple services, such as Spark and others. When a user selects a service, like Spark for example, the app will open a new tab displaying my page (service.html) with user information ...

Guide on utilizing angularjs $q.all() method with a dynamically generated set of promises

I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are gener ...