是否可以使用组件 属性 作为数据变量?

Is it possible to use a component property as a data variable?

我已经在下面复制了我当前的代码。我正在尝试动态生成 table headers 取决于 type 我作为道具传递给我的 tables 组件(排名和状态是我作为数据数组所拥有的在我的例子中)。

我通过在 header 计算值中使用 if 语句到 return 正确列表来完成此操作。

但是我不想为每个 type 添加额外的 if 语句。

有没有一种方法可以利用 type 道具直接绑定到匹配数据?

<div id="root" class="container">
    <tables type="stats">

    </tables>
</div>

Vue.component('tables', {
  template: `
  <table class="table">
    <thead>
      <tr>
        <th v-for="headers in header">{{ headers }}</th>
      </tr>
    </thead>
    <tfoot>
      <tr>
        <th v-for="footers in header">{{ footers }}</th>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <th>1</th>
        <td><a href="https://en.wikipedia.org/wiki/Leicester_City_F.C." title="Leicester City F.C.">Leicester City</a> <strong>(C)</strong>
        <slot></slot>
      </tr>
    </tbody>
  </table>
  `,

  data () {
    return {
      standings: ['Rank', 'Team', 'Wins', 'Losses'],
      stats: ['Number', 'Player', 'Position', 'RBI', 'HR']
    };
  },

  computed: {
    header() {
      if (this.type == 'standings') {
        return this.standings;
      } else {
        return this.stats;
      }
    }
  },

  props: {
    type: { required: true }
  }

});

如果您稍微更改了数据结构,则可以删除 if 语句。

  data () {
    return {
      types:{
        standings: ['Rank', 'Team', 'Wins', 'Losses'],
        stats: ['Number', 'Player', 'Position', 'RBI', 'HR']
      }
    };
  },
  computed: {
    header() {
      return this.types[this.type]
    }
  },
  props: {
    type: { required: true }
  }

这是一个例子。

Vue.component('tables', {
  template: `
  <table class="table">
    <thead>
      <tr>
        <th v-for="headers in header">{{ headers }}</th>
      </tr>
    </thead>
    <tfoot>
      <tr>
        <th v-for="footers in header">{{ footers }}</th>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <th>1</th>
        <td><a href="https://en.wikipedia.org/wiki/Leicester_City_F.C." title="Leicester City F.C.">Leicester City</a> <strong>(C)</strong>
        <slot></slot>
        </td>
      </tr>
    </tbody>
  </table>
  `,

  data () {
    return {
      types:{
        standings: ['Rank', 'Team', 'Wins', 'Losses'],
        stats: ['Number', 'Player', 'Position', 'RBI', 'HR']
      }
    };
  },
  computed: {
    header() {
      return this.types[this.type]
    }
  },
  props: {
    type: { required: true }
  }

});

new Vue({
 el: "#root"
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="root" class="container">
    <tables type="stats">

    </tables>
</div>