BootstrapVue conditional column in b-table

て烟熏妆下的殇ゞ 提交于 2020-05-24 06:09:49

问题


I'd like to only show one of my columns if the current user is an admin. I'm not sure how to do this with bootstrapVue. Any ideas?


回答1:


Here's a snippet based on Troy's comment.

I've added a custom property to the field object called requiresAdmin. This is not part of standard Bootstrap-Vue.

You can use this to filter out all the fields that require's the user to be an admin in a computed property. Based on whether the user is an admin or not. This makes it easy to add and remove fields that require's the user to be an admin.

new Vue({
  el: '#app',
  computed: {
    computedFields() {
      // If the user isn't an admin, filter out fields that require auth.
      if(!this.isUserAdmin)
        return this.fields.filter(field => !field.requiresAdmin);
        
      // If the user IS an admin, return all fields.
      else
        return this.fields;
    }
  },
  data() {
      return {
        isUserAdmin: false,
        fields: [
          { key: 'first', label: 'First Name' },
          { key: 'last', label: 'Last Name' },
          { key: 'age', label: 'Age' },
          { key: 'sex', label: 'Sex' },
          { key: 'secretActions', label: 'Secret Actions', requiresAdmin: true },
        ],
        items: [
          { first: 'John', last: 'Doe', sex: 'Male', age: 42 },
          { first: 'Jane', last: 'Doe', sex: 'Female', age: 36 },
          { first: 'Rubin', last: 'Kincade', sex: 'Male', age: 73 },
          { first: 'Shirley', last: 'Partridge', sex: 'Female', age: 62 }
        ]
      }
    }
})
<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.3.0/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.3.0/dist/bootstrap-vue.js"></script>

<div id="app" class="p-3">
  <b-btn @click="isUserAdmin = !isUserAdmin">
    Toggle admin user ({{ isUserAdmin }})
  </b-btn>
  <br /><br />
  <b-table :fields="computedFields" :items="items">
    <template v-slot:cell(secretActions)>
      <b-btn>Edit User</b-btn>
      <b-btn>Delete User</b-btn>
    </template>
  </b-table>
</div>


来源:https://stackoverflow.com/questions/61444698/bootstrapvue-conditional-column-in-b-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!