存储变量内部模板化循环结构的Vue建议?

时间:2017-07-14 01:32:38

标签: vue.js

给出以下代码

// Assuming records is an array of objects
// Record is of the form {"fname": "John", "lname": "Smith", "dob": 1499994497871}
// Field mapper is
[
    {
        "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()}
    }
]

// Assume findField returns the mapper instance for a given record in the records array

<div v-for="record in records">
    <div>
        <table class="table">
            <tbody>
                <tr v-for="(value, key) in record">
                    <th v-if="findField(key)">{{ findField(key).label }}</th>
                    <td v-if="findField(key)">{{ findField(key).render(value) }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

我正在四次调用findField()。

Vue建议将变量存储在循环结构中是什么?

换句话说,在第一个 tr 之后,类似于:

let localInstance = findField(key)

1 个答案:

答案 0 :(得分:0)

一种方法是使用组件。

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

修改模板以使用它。

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

&#13;
&#13;
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)
    }
  },
})
&#13;
<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>
&#13;
&#13;
&#13;