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?