Utilizing Vue.js for the selection of multiple elements

I am currently in the process of transitioning from jQuery to Vue, and I have encountered an issue when trying to select multiple elements within a single Vue instance.

For instance,

On my website, there are two posts each with a comment form. I want to use Vue to render the comment form for all the posts.

Below is the HTML:

<div class="post">
  <h1>This is the first post</h1>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, delectus, vero! 
    Aut adipisci fuga, dolorem optio sunt mollitia, debitis eius magni totam sint harum provident ipsa, 
    corporis eligendi dolorum hic!
  </p>
  <hr>
  <div class="vue-commenting"></div>
</div>

<div class="post">
  <h1>This is the second post</h1>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, delectus, vero! 
    Aut adipisci fuga, dolorem optio sunt mollitia, debitis eius magni totam sint harum provident ipsa, 
    corporis eligendi dolorum hic!
  </p>
  <hr>
  <div class="vue-commenting"></div>
</div>

The issue lies in the fact that Vue is only selecting the first div.vue-commenting element. As shown below,

https://i.sstatic.net/jHa02.png As depicted in the image, Vue is rendering the "Add a comment" button solely for the first element!

Here is my Vue code:

let app = new Vue( {
  el: '.vue-commenting',
  template: '#add-comment-template',
  data: {
    message: 'Comment section goes here ...',
    visibleForm: false
  },
  methods : {
    ToggleReplyForm: function ( event ) {
      event.preventDefault()
      this.visibleForm = ! this.visibleForm
    }
  }
} )

Template Code:

<script type="text/x-template" id="add-comment-template">
  <div>
    <a 
      href="#"
      class="btn btn-success"
      v-on:click="ToggleReplyForm">
      Add a comment
    </a>
    <div class="clearfix"></div>

    <br/>

    <div 
      v-if="visibleForm"
      class="panel panel-default">

      <div class="panel-heading">
        Comment Form
      </div>
      <div class="panel-body">
        <div class="form-group">
          <label for="un">Name</label>
          <input type="text" class="form-control" id="un">
        </div>
        <div class="form-group">
          <label for="uc">Comment</label>
          <textarea class="form-control" id="uc" rows="3"></textarea>
        </div>
      </div>
      <div class="panel-footer">
        <button
          class="btn btn-warning">
          Post Comment
        </button>
      </div>
    </div>

  </div>
</script>

How can I properly select multiple elements in Vue?

Answer №1

Instead of assigning a class to el and expecting it to generate a Vue instance for each matching item, remember that it doesn't function this way. It's better to provide a single element containing all the elements you want Vue to manage, or iterate through each element separately and create a new Vue instance for each one. My recommendation would be to go with the first option.

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

What is the best way to combine an additional array into a different project attribute?

There are 2 arrays being used. This is the content of userGroups: console.log(this.items) [ { "id": 63, "name": "URLGROUP-1643836551908" } ] The contents of urls are shown below: userGroup can contain ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

The issue with Vue email validation not functioning correctly when the div ID is removed

I'm completely new to Vue.js and I'm keen on understanding why removing the div with id "app" in this codepen example (not mine) leads to the failure of rendering the email validator input field. <div class="container" id="app&q ...

Randomly retrieving Vue data from a JSON source

For my first venture into creating a quiz app with Vue and Tailwind, I want to ensure that the quiz's content appears different each time it is accessed. Currently, I have set up my Vue component to display data from a JSON file in the following manne ...

Iterating through data to showcase vertical columns for a specific time span of 3 years, highlighting only the months with available data

If data has been available for every month over the past 3 years, I need it to be displayed in a specific format. You can refer to this example fiddle for reference: https://jsfiddle.net/bthorn/ncqn0jwy/ However, there are times when certain months may no ...

When trying to load AJAX, it does not function properly unless the page is refreshed

I'm currently working on a web page and encountering some difficulties. Within my HTML, I have two divs that are refreshed using AJAX. The issue is that the content loading seems to be inconsistent unless I manually refresh the page or implement a tim ...

Regex substitute every instance of the phrase CONTAINED within brackets

I am looking to replace all instances of text within brackets, including the brackets themselves, in a given string. The specific text to be replaced will be stored in a variable in Javascript. Using a simple regex in a replace method won't work due t ...

Duplicate the LI element in a way that it is inserted after the original LI instead of at the end

I am looking for a way to clone an item immediately after clicking on it instead of cloning it at the end of the list. Currently, it always clones to the END and adds it after the last LI in the list. Here is a link to the jsFiddle I created jsfiddle test ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...

Is it possible for a JavaScript .execute function to be executed synchronously, or can it be transformed into an Ajax

Currently, I am utilizing the ArcGIS API for Javascript which can be found at this URL: The JavaScript code snippet I'm working with appears to be running asynchronously. Is there a way to convert it to run synchronously or potentially transform it i ...

What is the process for incorporating the JavaScript "star" feature from Google's search results page?

In the Google search results, each entry has a star that users can click to indicate if the result is good or not. This feature is likely implemented using JavaScript. I'm interested in implementing a similar function in my own web application. I wou ...

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

Updates to Providers in the latest release of Angular 2

When working with angular 2.0.0-rc.1, we implemented a Provider using the new Provider method as shown in the code snippet below: var constAccessor = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => EJDefaultValueAccessor), ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

"Enhancing the speed of the JavaScript translate function when triggered by a scroll

I am facing an issue with setting transform: translateY(); based on the scroll event value. Essentially, when the scroll event is triggered, #moveme disappears. For a live demonstration, please check out this fiddle: https://jsfiddle.net/bo6e0wet/1/ Bel ...

Passing values to the next page is not functioning as expected

I'm having trouble passing a variable called userId to the next page in my application. Below is the snippet of code I am using to pass the value to the next page: $.each($.parseJSON(data), function(key, value) { var userId = value.id_user; ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...