Loop through the v-for based on the input number that was selected

I'm looking to accomplish the following: if a user selects input X (a number between 1 and 10), I want to render a specific vue component X times. It seems to work if I use v-for n in 10, but not when I use variables.

    <template>
<div>
    <select v-model="selected" >
    <option disabled value="">Please select one</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    </select>

    <span v-for="n in selected" :key="n">{{"hey"}}</span>


</div>
</template>

<script>
export default {
  data: function () {
      return {
        selected: ''
      }
  },
}
</script>

Any quick ideas on how to solve this? Currently, I am returning some string temporarily (it should actually be a component, but I can replace the string with the component later), which works if I replace "selected" with a number like 5 (then it renders 5 times).

Also, just as a side note: when I replace "hey" with n, it displays the correct number. However, it shows the number itself, not the number of times (i.e., it displays 1 2 3 ... but only once).

Answer №1

Make sure to assign value as a number, like this :value="1"

For example:

new Vue({
  el: "#app",
  data: {
    selected: 0
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" style="padding:20px">
  <select v-model="selected" >
    <option disabled :value="0">Please select one</option>
    <option :value="1">1</option>
    <option :value="2">2</option>
    <option :value="3">3</option>
  </select>
  <ol>
    <li v-for="i in selected">{{ 'hey' }}</li>
  </ol>
</div>

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

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Re-Rendering Component in React Continuously Keeps Checkbox Checked Event Flowing

I am working on a material ui checkbox formgroup that is generated dynamically based on data received from an API. Essentially, the user is presented with a question and a set of answers. The user checks all the valid answers and clicks 'next'. I ...

Generate a random number in PHP with the click of a button

Hello, I have a scenario where I am working with two PHP pages. One page generates random numbers and the other displays them on a page refresh. I would like to find a way to retrieve the current random value by clicking a button instead of refreshing t ...

Attempting to send form data along with an additional parameter using axios

I am working on a form that allows users to upload single files using a FormData object. Along with the file, I also need to assign it to a specific Group. The challenge I'm facing is how to include the group object id in the request. Below is the c ...

issue with duplicating DOM element using function

My situation is unique from the one described in this post. The code mentioned there is not functioning as expected when clicking the clone button. I have even provided a video explanation of how that code works. Unfortunately, I haven't received any ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

Creating a customizable range input for pixel values: a step-by-step guide

I am looking to design a pixel range input. Here is an example: let slider = document.querySelector("input"); slider.addEventListener("change", () => { console.log(slider.value); }); <input type="range" min="5px" max="50px"> However, the r ...

managing websocket connections across various instances

Looking to grasp the concept of managing websockets across multiple instances in order for it to be accessible by all instances. For example, with three nodes running connected through a load balancer, data needs to be emitted on a specific socket. My init ...

Tips for properly invoking an asynchronous function on every rerender of a component in Vue.js

Situation: An analysis module on a website that needs to display three different data tables, one at a time. Approach: The module is a component containing three buttons. Each button sets a variable which determines which table to render. Depending on the ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

What is the best way to end a table row after every group of four items?

I am working with a Handlebars template to display an array of movies in a table with four columns. Currently, I have set up a HBS helper in my code: app.engine('handlebars',exphbs({ defaultLayout: 'main', helpers: { n ...

Is your Laravel and vue js "add to cart" button malfunctioning?

Hey there! I'm currently working on an e-commerce project using Laravel and Vue. I have successfully managed to add products to the cart, but I'm facing an issue where the quantity in the cart remains at 0 until I refresh the page. I've trie ...

What is the best way to position a single element in React using the Grid Component without causing any overlap?

I am struggling with positioning 3 components on my react page: PageHeader, SideMenu & FeatureList (which consists of Display Cards). Here is the code for each component: App.js // App.js code here... PageHeader.js // PageHeader.js code here... SideMenu ...

Developing secure web applications using Node.js and Express with HTTPS encryption

I am attempting to utilize express with node.js using https. Below is the relevant code for this segment: var express = require("express"); var app = express(); var https = require('https'); var privateKey = fs.readFileSync('./sslcert/myke ...

Setting up a Contact Email for your Nuxt Static Generated site: A Step-by-Step Guide

I have a website built on Nuxt and hosted on Netlify. I utilized the 'static' method in my nuxt.config.js file to generate the dist folder. My goal is to trigger an email notification whenever a user submits a contact form on my site. It functio ...

Issue with function execution in MVC after invoking from jstree

My jquery code is supposed to trigger the MVC function call: $(document).ready(function () { alert("ddddd"); $("#divJsTreeDemo").jstree({ "plugins": ["json_data"], "json_data": { "ajax": { "type": "POST", "url": "/W ...

What is the process of creating a deep clone of the state and reverting back in Vuex?

Looking to create a snapshot or clone of an object property within the Vuex tree, make modifications, and have the option to revert back to the original snapshot. Context: In an application, users can test out changes before confirming them. Once confir ...

When conditions are met, all items are added to the array

In my Angular app, I have a user list that I am trying to filter based on the condition age > 45. However, all users are being pushed into the validForScheme array instead of just those meeting the condition. I am unable to figure out what is going wron ...

such as in the post schema, the word "like" does not

like not removing from post model likeSchema .findOne({$and: [{post: postId ,user: userId}]}) .exec((err, result) =>{ if (result) { db.likeSchema .findOne( { $and ...