4
votes

I'm trying to make Vue.js instantiate it's components from existing HTML templates and I cannot find any reasonable information on doing that. I'm using non-JavaScript backend framework and Vue.js added in as a normal .js file in the view stack.

Let's say I have the HTML structure looking like this:

<div id="vueApp">
  <div class="vueComponent">...</div>
  <div class="vueComponent">...</div>
  <div class="vueComponent">...</div>
</div>

Then I'm trying to enable it with JavaScript like this (mixing jQuery and Vue for safety):

<script>
  // declare Vue component
  Vue.component('irrelevantName', {
    template: '.vueComponent',
    data: function() {

      return { something: false }
    }
  });

  // launch Vue app
  jQuery(document).ready(function() {

    var vueApp = new Vue({
      el: '#vueApp',
      created: function() {

         // TODO: some method that will read/parse the component data, do binding, whatever
      }
    });
  });
</script>

This kind of approach worked perfectly for whenever I had a precisely declared and pointed <template> tag within the HTML structure and the component was supposed to be just a single one. In this case though I'm trying to instantiate n ones identified by a CSS class. I am aware that one possible approach would be passing all the component data as hidden <input> with JSON-ized array/Collection data, and then asking vueApp to create single-template-driven components on the fly from this data, though that seems a bit tedious approach.

Any suggestions? Thanks in advance!

1

1 Answers

2
votes

I believe you might be thinking about this the wrong way. Vue binds to a single element, so if you want multiple elements to be manipulated, what you can do is create a new Vue instance around div#vueApp and create the components inside of that with Vue templates, like so:

Vue.component('vue-comp', {
  data: function () {
    return {
      something: false
    }
  },
  template: '<div class="vue-comp"></div>'
})

let vueApp = new Vue({
  el: '#vueApp',
  created: function() {
    
  }
});
div#vueApp {
  padding: 1rem;
  background: #CD545b;
  display: inline-block;
}

div.vue-comp {
  height: 50px;
  width: 50px;
  margin: 0 1rem;
  background: #236192;
  display: inline-block;
}
<script src="https://unpkg.com/vue"></script>
<div id="vueApp">
  <vue-comp></vue-comp>
  <vue-comp></vue-comp>
  <vue-comp></vue-comp>  
</div>