Vue.js Bind Vue To Multiple Html Elements Of Same Class Name

September 13, 2017

Assuming you would like to bind Vue to multiple existing <div class="comment"> element in HTML.

<div class="comment" data-id="1">

<div>

<div class="comment" data-id="2">

<div>

...

You would need to find all elements by class name and create individual Vue object for each element.

Note: el: '.comment' would only bind to the first element.

var comments = {
  "1": {"content": "Comment 1"},
  "2": {"content": "Comment 2"}
}

$('.comment').each(function () {
  var $el = $(this)

  var id = $el.attr('data-id')
  var data = comments[id]

  new Vue({
    el: this,
    data: data,
    template: '<div class="comment">{{ content }}<div>'
  })
})
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.