首页 > 解决方案 > vuejs:如何在相同组件中传递共享道具?

问题描述

我正在使用来自 Bootstrap Vue 的表格组件,我想知道是否有办法避免每次都为此组件编写完全相同的道具。

例如,假设我正在将组件用于用户表,如下所示:

  <b-table
    id="users-table"
    :busy.sync="isBusy"
    :items="fetchData"
    :fields="fields"
    :current-page="currentPage"
    :per-page="perPage"
    :sort-by.sync="sortBy"
    :sort-desc.sync="sortDesc"
    :no-local-sorting="true"
    :filter="filter"
    primary-key="id"
    responsive
    small
    show-empty
  >
      <template v-slot:cell(userName)="data">
        // ...
      </template>

      <template v-slot:cell(actions)="data">
         // ...
      </template>
  </b-table>

现在,如果我想使用相同的b-table组件但产品列表,我将不得不重写/重新传递完全相同的道具给这个组件:

 <b-table
    id="products-table"
    :busy.sync="isBusy"
    :items="fetchData"
    :fields="fields"
    :current-page="currentPage"
    :per-page="perPage"
    :sort-by.sync="sortBy"
    :sort-desc.sync="sortDesc"
    :no-local-sorting="true"
    :filter="filter"
    primary-key="id"
    responsive
    small
    show-empty
  >
      <template v-slot:cell(productPrice)="data">
        // ...
      </template>

      <template v-slot:cell(actions)="data">
         // ...
      </template>
  </b-table>

这是非常重复的......

有没有办法做这样的事情?

  <b-table
    id="users-table"
    someObject
  >
      <template v-slot:cell(userName)="data">
        // ...
      </template>

      <template v-slot:cell(actions)="data">
         // ...
      </template>
  </b-table>

哪里someObject会包含这个组件的通用道具?

标签: vue.jsbootstrap-vue

解决方案


您可以将对象的属性作为道具传递:

<b-table 
  v-bind="options"
>
  ...
</b-table>

data() {
  return {
    options: {
      filter: filter,
      fields: fields,
      ...
    }
  }
}

结果:

<b-table
  :filter="options.filter"
  :fields="options.fields"
>
  ...
</b-table>

https://vuejs.org/v2/guide/components-props.html#Passing-the-Properties-of-an-Object


推荐阅读