Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code.

My objective is to apply this directive to an element and provide a Guid to it (for managing conditional rendering based on user permissions):

v-permission="'4ECE1FD4-4019-4CA2-AB9E-0A555CCBDB5B'"

Currently, I am using the directive's bind method to add display: none to the element, which successfully hides the content. However, for better performance, I would like to avoid rendering the element altogether.

Does anyone have any suggestions on how I can accomplish this?

Here is the snippet of the current directive code:

import Vue from 'vue'

Vue.directive('permission', {
  bind: function (el, binding, vnode) {
    if (binding.value) {
      let hasPermission = 
vnode.context.$store.getters.hasApiPermission(binding.value)
      if (!hasPermission) {
        el.style.display = 'none'
      }
    } else {
      console.error('You must specify a permission ID')
    }
  }
})

Answer №1

One way to achieve this is by utilizing the inserted hook:

inserted: triggered when the element is inserted into its parent node.

Here’s an example snippet of code showcasing how it works:

Vue.directive('permission', {
  inserted: function (el, binding, vnode) {
    if (binding.value) {
      let hasPermission = 
vnode.context.$store.getters.hasApiPermission(binding.value)
      if (!hasPermission) {
        el.parentNode.removeChild(el)
      }
    } else {
      console.error('Please provide a permission ID')
    }
  }
})

Nevertheless, it is recommended to leverage the built-in v-if directive for a more efficient solution. With Vue 2 operating on virtual DOM, it will not render if the condition evaluates to false. On the other hand, using a custom directive like in this case may result in initial rendering followed by removal.

Answer №2

It's uncertain whether achieving what you desire is feasible. However, it's also unclear if it's truly necessary. In my opinion, a structure like this,...

<tag v-if="getPerm('4ECE1FD4-4019-4CA2-AB9E-0A555CCBDB5B')">
  ...
</tag>

...is sufficiently declarative.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The `pages` directory seems to be missing. Package error encountered while using NextJS

As I strive to create a NextJS executable application for Windows, an irritating error has arisen: (node:18500) UnhandledPromiseRejectionWarning: Error: > Couldn't find a pages directory. Please create one under the project root I assure you, th ...

The XML content fails to display after initiating an AJAX request

Attempting to create an ajax call and accessing a field from the table on the server yields the following: <PushProperty><Status ID = "1"> Success </Status><ResponseID> b3633c9eeb13498f </ResponseID><ID> 9098 & ...

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

Is there a way for me to monitor a prop using the composition api?

Is there a way to trigger a function upon prop update? The parent container structure is as follows: <div> <Maintable :type="typeRef" :country="countryRef" /> </div> And here's the child container code: e ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...

Material-UI: The Mystery of Missing CSS Properties

Struggling to apply a CSS class to an element from Material-UI: bw:hover { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } Tried using makeStyles: import { makeStyles } from '@material-ui/core/styles' ...

Transferring slot data from Parent components to Child Components

I've created a custom component called async-select based on another component, vue multiselect. Here's how: Check out the code here: https://jsfiddle.net/2x7n4rL6/4/ Although vue-multiselect provides several slots, I want to utilize them withi ...

Prevent redirection in JavaScript

My current script is designed to detect an Android device and then redirect the user to "android.html". Once on the "android.html" page, the user has the option to either download an app or click "CONTINUE" to proceed to "index.html". However, there seems ...

bespoke JavaScript confirmation dialogue box

After customizing a confirmation box for the logout feature, I encountered an issue. When the user presses cancel, the box closes and control remains on the same page as expected. However, when the user clicks yes to logout, nothing happens. Could anyone p ...

What is the process for aligning Item1 to the left and Item2 & Item3 to the right using MUI React?

I'm working on a component that contains three different Typography components. I need to align "summary" to the left, while 'miles' and 'duration' should be aligned to the right. https://i.stack.imgur.com/7e9sY.png Here's t ...

Mastering linear regression calculations using vue.js and chart.js

Take for instance, with the current dataset, I am looking to showcase a linear regression I managed to do this in Vista and now I need guidance on how to proceed with the calculation. I am not too familiar with using the formula Here is my HTML: <canva ...

"Attempting to connect to REST server using angularjs $resource. Unexpectedly, the success callback does not

After attempting to set up a REST server on Nodejs and accessing it from AngularJS using $resource for the first time, I have encountered some issues... In my controller, I am trying to load a JSON object (shopping cart) upon login for existing users or c ...

When HTML elements are dynamically inserted through JavaScript using quilljs, they may cause conflicts with the layout properties

I am currently working on creating a simple webpage layout similar to that of Stack Overflow, with a sidebar and a main content area that can scroll. In my case, the content area is intended to host a QuillJS text editor. To integrate the QuillJS editor i ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Iterate endlessly over CSS styles in Angular 4

I'm looking to create a website background 'screensaver' by looping through an array of background URLs with a delay between switches. Currently, I have the array stored in my .ts file and I am using the NgFor directive in my HTML. However, ...

An abundant array of options spread across numerous dropdown menus

I have been tasked by a client to do something new that I haven't done before, so I am seeking the best approach. The project involves creating a form with three dropdown menus where users can select from thousands of options. For instance: Users mu ...

Issue with React Hook Form - frequent failure in submitting the form

I have implemented the useForm hook from https://www.npmjs.com/package/react-hook-form. However, I am encountering some inconsistent behavior where it sometimes works immediately, sometimes requires a page refresh to work, and sometimes doesn't work a ...

Exploring the Issue of Flickering in 3D Models with Three.js and Potree

Currently, I am working with a gltf model from this link: using Three.js and Potree. However, I am facing an issue with the model flickering. I have gone through similar posts on this topic like Flickering planes and Texture/model flickering in distance ( ...

Struggling with customizing the style of react mui-datatables version 4

Currently, I am utilizing "mui-datatables": "^4.2.2", "@mui/material": "^5.6.1", and have attempted to customize the styling in the following manner: Refer to the Customize Styling official documentation for more details // CUSTOMIZING MUI DATATABLES imp ...

Comparing the map function and for loop in the Puppeteer package for Node.js

I experimented with the Puppeteer package in NodeJS and noticed a significant difference in functionality between using the map function versus a for loop. Here is an illustration of what I observed: Using the map function: data.map(async(info) =>{ ...