Search code examples
vue.jsbootstrap-vue

vuejs: How to pass shared props in same components?


I'm using a table component from Bootstrap Vue and I'd like to know if there is a way to avoid having to write each time the exact same props for this component.

For instance, let's say I'm using the component for a users table like this:

  <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>

Now, if I want to use the same b-table component but for a list of products, I'm gonna have to rewrite/repass the exact same props to this component:

 <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>

Which is very repetitive...

Is there a way to do something like that ?

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

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

Where someObject will contain the common props for this component ?


Solution

  • You can pass an object's properties as props:

    <b-table 
      v-bind="options"
    >
      ...
    </b-table>
    
    data() {
      return {
        options: {
          filter: filter,
          fields: fields,
          ...
        }
      }
    }
    

    Result:

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

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