Search code examples
javascriptvue.jsvuejs2vue-componentvue-router

How to Disable the Vue component (div-tag)?


I am trying to disable the VUE component based on the user access settings. Now, I am able to hide the component from the UI, but after every re-render, the component is getting active. I don't just want to hide the component; I want to prevent the user from clicking the component. I couldn't find the exact solution to my problem. Thank you in advance.

This is the route and beforeEach route condition:

 {
    path: "/settings/overview",
    name: "SettingsOverview",
    component: PageSettingsOverview,
    meta: {
      requiresAuth: true,
      showComponent: true,
      componentAccessPermissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    },
  },

**beforeEach**

 const currentLogUser = store.getters["auth/currentUser"];
    if (
      currentLogUser !== null &&
      to?.meta?.componentAccessPermissions !== undefined
    ) {
      for (let i = 0; i < currentLogUser.teams.length; i++) {
        const team = currentLogUser.teams[i];
        const valPermissions = team.permissions
          .filter((item) => {
            return to.meta.componentAccessPermissions.includes(
              item.permissionType
            );
          })
          .map((item) => {
            return item.permissionType;
          });
        const allowAccess = to.meta.componentAccessPermissions.every((i) =>
          valPermissions.includes(i)
        );
        if (!allowAccess) {
          to.meta.showComponent = false;
        } else {
          to.meta.showComponent = true;
        }
      }
    }

VueFile:

<div class="col-12 col-md-4" v-if='$route.meta.showComponent' @click.prevent>
        <router-link class="card" to="/administration" >
          <div class="card-img-top">
            <i class="hi hi-people" />
          </div>
          <div class="card-body">
            <h5 class="card-title">Teams & Users</h5>
          </div>
        </router-link>
      </div>

Solution

  • Toggle pointer-events in CSS to prevent the user from interacting with your component;

    <div :class="`col-12 col-md-4 ${$route.meta.showComponent ? 'pe-none' : ''}`">
        <router-link class="card" to="/administration" >
            <div class="card-img-top">
                <i class="hi hi-people" />
            </div>
            <div class="card-body">
                <h5 class="card-title">Teams & Users</h5>
            </div>
        </router-link>
    </div>
    

    If you don't have bootstrap;

    <div class="col-12 col-md-4" :style="`${$route.meta.showComponent ? 'pointer-events: none' : ''}`">
        <router-link class="card" to="/administration" >
            <div class="card-img-top">
                <i class="hi hi-people" />
            </div>
            <div class="card-body">
                <h5 class="card-title">Teams & Users</h5>
            </div>
        </router-link>
    </div>