[Vuejs]-Vue Recommendation for Storing Variable Inside Templated Looping Structure?

0👍

One way is to use a component.

Vue.component("row", {
  props:["map", "value"],
  template:`
    <tr>
      <th v-if="map">{{ map.label }}</th>
      <td v-if="map">{{ map.render(value) }}</td>
    </tr>
  `
})

And modify your template to use it.

<tr is="row" v-for="(value, key) in record" 
             :map="findField(key)"
             :value="value">
</tr>
console.clear()

const fieldMap = [{
    "name": "fname",
    "label": "First Name",
    "render": function(val) {
      return val
    }
  },
  {
    "name": "lname",
    "label": "Last Name",
    "render": function(val) {
      return val
    }
  },
  {
    "name": "dob",
    "label": "Date of Birth",
    "render": function(val) {
      return new Date(val).toDateString()
    }
  }
]

const records = [{
    "fname": "John",
    "lname": "Smith",
    "dob": 1499994497871
  },
  {
    "fname": "John",
    "lname": "Smith",
    "dob": 1499994497871
  },
  {
    "fname": "John",
    "lname": "Smith",
    "dob": 1499994497871
  }
]

Vue.component("row", {
  props: ["map", "value"],
  template: `
    <tr>
      <th v-if="map">{{ map.label }}</th>
      <td v-if="map">{{ map.render(value) }}</td>
    </tr>
  `
})
new Vue({
  el: "#app",
  data: {
    records
  },
  methods: {
    findField(key) {
      return fieldMap.find(m => m.name === key)
    }
  },
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <div v-for="record in records">
    <div>
      <table class="table">
        <tbody>
          <tr is="row" v-for="(value, key) in record" :map="findField(key)" :value="value">
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
👤Bert

Leave a comment