[Vuejs]-Getting HTML elements as v-bind data

0👍

Vue has no built-in mechanism to build an object from arbitrary HMTL. (The virtual DOM works in the opposite way, building a virtual HTML structure from objects.)

In this specific case, it’s not hard to create the object in plain JavaScript

var tableEl = document.querySelector("table");
var keys = Array.from(tableEl.tHead.rows[0].cells).map(el => el.textContent.trim());
var array = Array.from(tableEl.tBodies[0].rows).map(row => {
  var entry = {};
  keys.forEach((key, index) => {entry[key] = row.cells[index].textContent.trim();})
  return entry;
});

0👍

Yes you can do it with vue :

First you need to create the component with the following template:

         var template = "
          <table>
            <thead>
               <th>Name</th><th>DOB</th><th>Sex</th>
           </thead>
           <tbody>
              <tr v-for="obj in data" :key="obj.Name">
                  <td>{{obj["Name"]}}</td>
                  <td>{{obj["DOB"]}}</td>
                  <td>{{obj["Sex"]}}</td>
               </tr>
            </tbody>
          </table>"

then just pass the data you want to display on the component below as prop (bind)

run the following snippet :

// the component
Vue.component('some-component',{  
          props : ['data'],
          template : '<table><thead><th>Name</th><th>DOB</th><th>Sex</th></thead><tbody><tr v-for="obj in data" :key="obj.Name"><td>{{obj["Name"]}}</td><td>{{obj["DOB"]}}</td><td>{{obj["Sex"]}}</td></tr></tbody></table>'
})
// the instance
new Vue({
   el : '#app'
})
table,th,td {
   padding : 10px;
   border : 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 <some-component  v-bind:data="[
            {'Name':'John', 'DOB': '01 Jan', 'Sex' : 'M'},
            {'Name':'Jane', 'DOB': '25 Dec', 'Sex' : 'F'},
            {'Name':'foo', 'DOB': '22 Dec', 'Sex' : 'M'},
            {'Name':'bar', 'DOB': '21 Dec', 'Sex' : 'M'}
             ]">
</some-component>
</div>

Leave a comment