Using the v-for directive in Vue.js without the need for an HTML element

I am new to learning Vue.js and currently working on a demo for input elements practice. Below is the code I have written:

HTML

<div id="inputDiv">
  <form action="">
    <input type="text" v-model="first_name">
    <input type="text" v-model="last_name">
    <input type="email" v-model="email">
    <div>
      <input type="radio" :name="gender" v-model="gender" value="male">Male
      <input type="radio" :name="gender" v-model="gender" value="female">Female
    </div>
    <textarea v-model="address" id="" cols="30" rows="10"></textarea>
    <br>
    <div v-for="hobby in hobbies">
      <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}
    </div>
  </form>
</div>

Script

const inputApp = new Vue({
  el: '#inputDiv',
  data: {
    first_name: '',
    last_name: '',
    email: '',
    gender: 'male',
    address: '',
    userHobbies:[],
    hobbies: ['Reading', 'Cricket', 'Cycling', 'Hiking']
  }
})

In order to display Hobby with label without using a parent div, I tried iterating directly in the input element as shown below:

<input 
  type="checkbox" 
  v-for="hobby in hobbies" 
  v-model="userHobbies" 
  v-bind:value="hobby"
>{{hobby}}

However, this approach led to an exception [Vue warn]: Property or method "hobby" is not defined on the instance. Is there any alternative way to achieve iteration over object elements without including an HTML element?

Answer №1

Surround the code with a template tag to ensure it does not show up in the final HTML output:

<template v-for="hobby in hobbies">
    <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}
</template>

For better markup semantics, consider using a label tag instead:

<label v-for="hobby in hobbies">
    <input type="checkbox" v-model="userHobbies" v-bind:value="hobby"> {{hobby}}
</label>

Answer №2

To include a template within a div, remember that the template is not displayed on the web page:

  <div id="inputContainer">
    <form action>
      <input type="text" v-model="first_name">
      <input type="text" v-model="last_name">
      <input type="email" v-model="email">
      <div>
        <input type="radio" :name="gender" v-model="gender" value="male">Male
        <input type="radio" :name="gender" v-model="gender" value="female">Female
      </div>
      <textarea v-model="address" id cols="30" rows="10"></textarea>
      <br>
      <template v-for="interest in interests">
        <input type="checkbox" v-model="userInterests" v-bind:value="hobby">
        {{interest}}
      </template>
    </form>
  </div>

Answer №3

One issue that arises is the string interpolation {{hobby}} occurring outside of the loop after the tag, causing an error in this specific instance. To resolve this, it is necessary to wrap it inside something.

If using a div is not your preference, you can opt for a label instead which fits more naturally in this scenario. By clicking on the label, the checkbox will automatically be selected.

<label v-for="hobby in hobbies">
    <input type="checkbox" v-model="userHobbies" v-bind:value="hobby"> {{hobby}} <br>
</label>

new Vue({
  el: '#inputDiv',
  data: {
    first_name: '',
    last_name: '',
    email: '',
    gender: 'male',
    address: '',
    userHobbies:[],
    hobbies: ['Reading', 'Cricket', 'Cycling', 'Hiking']
  }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="inputDiv">
<form action="">
    <input type="text" v-model="first_name">
    <input type="text" v-model="last_name">
    <input type="email" v-model="email">
    <div>
        <input type="radio" :name="gender" v-model="gender" value="male">Male
        <input type="radio" :name="gender" v-model="gender" value="female">Female
    </div>
    <textarea v-model="address" id="" cols="30" rows="10"></textarea>
    <br>
    <label v-for="hobby in hobbies">
        <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}
        <br>
    </label>
</form>
{{ userHobbies | json }}
</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

Error Message: Unknown Custom Element <b-nav-brand> in Bootstrap-Vue.JS

I'm currently developing a Vue application and I've integrated the bootstrap-vue navbar component from the official example into my project. However, when I run my application, Vue keeps throwing a warning in the console about an unknown custom e ...

While looping through a JSON object and converting it to a string, the script is causing

I'm facing an issue with my webpage where I retrieve a JSON object from a URL and convert it into a string. Depending on whether the string is true or false, I want the div to either fade or remain unchanged. The JSON object obtained from the URL loo ...

Challenges with JavaScript and JQuery - Extracting and Displaying YouTube Information on Website

While I have some experience with Javascript and JQuery, my latest project on FirstPersonTheater.net is not going as planned. I am using PHP to generate a video ID in javascript code to retrieve information about YouTube videos such as title, uploader, vie ...

Tips for managing perspective distortion in THREE.PerspectiveCamera

My aim is to display a collada object and position it perfectly over an image with this object. https://i.sstatic.net/LCKZh.jpg Imagine that I have an image rendered by the v-ray renderer in 3ds max (green one) and a collada object that I render using ...

The download window is malfunctioning and unable to save the file

I'm currently developing an ASP.NET Web Form application with a specific requirement: to display a popup box for downloading an Excel file when the user clicks on a link. This link is located within a popup page, not on the main ASPX page. Here' ...

Is there a way to stop mouse panning in ThreeJs OrbitControls without affecting the ability to pan using keys?

My goal is to prevent users from panning with their mouse while still allowing them to pan using the keys. When I use controls.enablePan = false;, it disables key panning as well. Trying to rebind the mouse buttons requires me to assign a button to Orbit ...

Ways to retrieve every span within a string variable that possesses a specific class designation

I'm having trouble listing out all spans with the class "ansspans." There may be one or more span elements with the "ansspans" class, and I need to retrieve them along with their content in order to iterate through them. Can someone explain how to do ...

Using jQuery to fetch and display content only when the user hovers over

Looking to optimize page loading speed by minimizing the loading time of social icons such as Facebook Like and Twitter follow buttons. Considering displaying a static image of the like buttons initially, with the actual buttons appearing on mouse hover. ...

unable to establish connection due to port error in node.js

While executing node app.js I encountered the following error message info - socket.io started warn - error raised: Error: listen EACCES This snippet shows all the JavaScript code within the application. After running sudo supervisor app.js T ...

Is there a way to change an object into a string in JavaScript without using JSON.stringify?

Usually I wouldn't approach it this way, but for the sake of a practice exercise, I am attempting to convert an object without relying on JSON.stringify(). Take a look at the object in question: obj = { num: 0, string: "string", func: function ...

The magical unveiling of words through the art of animation

After spending considerable time learning how to code, I find myself seeking assistance in creating a specific animation. For the past two days, I've been struggling to bring my vision to life (see attached image). Unfortunately, my current knowledge ...

Strategies for disabling middle mouse button default behavior in Vue

When I use @click.middle.stop.prevent="test", the default scroll wheel still shows up despite it detecting the middle mouse click and calling my function. Is there a way to prevent this from happening? ...

Attempting to conceal something once the input has been chosen

Check out my code on Fiddle Everything you need to know is in the fiddle. Here's the issue: I want the text to disappear when I click on the input field to start typing something. When I focus on the input, I want the text to vanish and only re ...

This as well as its parent node

I am looking to implement a function where an element is manipulated if a child of it is clicked (by adding a CSS class to it). My current approach is as follows: function mahlzeitRaus() { console.log("Out"); //this.className += " not"; this. ...

Issue with dynamic creation of menu in React Material UI where onClose function is unable to reference a variable inside the function

As I develop an app, I have chosen to dynamically construct the settings menu based on a JSON file. { categories: [ { name: "General", index: 1, items: [{ name: "Dark Mode", index: 1 ...

Retrieve the value from the URL by parsing it using JSON

My goal is to extract the asciiName from a specific URL: http://services.gisgraphy.com/geoloc/search?lat=21.283300399780273&lng=72.9832992553711&radius=10000<br> I am utilizing ajax jsonp for this task. Below is the complete code snippet ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

Internet Explorer 9 fails to recognize angular objects when used inside ngRepeat

One issue I encountered was with the ng-include and ng-controller nested inside an ng-repeat, causing some unexpected behavior in Internet Explorer: Here is a snippet from main.html: <section ng-repeat="panel in sidepanels"> <h2 class="twelve ...

Updating values in Vuex stores

Currently, I am delving into Vuex and facing a roadblock in my endeavor to have the number value change each time the p-element is clicked. The mutation responsible for this is called changeNumber. Additionally, I aim to display the updated number value ...

Implementing Event Handlers Post-Infinite Scroll Refresh

I have incorporated the infinite scroll feature using a plugin that can be found at this website. This plugin helps in loading page content seamlessly. One jQuery event listener that I have set up is as follows: $('.like-action').on('click ...