Creating a conditional rendering component attribute in VueJS

We are looking to modify our frontend in order to dynamically disable certain elements (such as buttons) based on a user's specific permissions to perform an action. Our goal is to maintain clean code by implementing something like this:

<button reqPermission="edit">

The idea is for this to trigger a JavaScript method that connects to our permission service, allowing Vue to render the element and enable it only if the request returns a truthy value.

While I am not very familiar with VueJS, I am hoping to avoid using v-if="..." as it may clutter our codebase. Any suggestions on creating a "custom attribute" that can influence component rendering would be greatly appreciated. My research led me to https://forum.vuejs.org/t/how-to-conditionally-render-a-component/69687/6

Answer №1

If you're looking to deactivate it based on a boolean value, you can achieve this within the Vue template syntax:

<button :disabled="!hasPermission.edit">

If your intention is to avoid displaying the button altogether rather than just disabling it, consider using v-if instead of :disabled.

If the boolean needs to be fetched from a backend source, I suggest utilizing a vuex store action to retrieve the user permissions and conditionally render based on the store's status:

<template>
  <button :disabled="!isFetching && !userPermissions.edit">
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'customButton',
  computed: {
    ...mapState('permissionModule', ['isFetching', 'userPermissions']),
  },
  mounted() {
    this.$store.dispatch('permissionModule/getUserPermissions')
  },
}
</script>

export default {
  namespaced: true,
  state: {
    isFetching: false,
    userPermissions: {
      edit: false,
      view: false,
    },
  },
  mutations: {
    toggleIsFetching(state, isFetching) {
      state.isFetching = isFetching
    },
    setUserPermissions(state, userPermissions) {
      state.userPermissions = userPermissions
    },
  },
  actions: {
    async getUserPermissions() {
      this.commit('permissionModule/toggleIsFetching', true)

      const user = await fetchCurrentUserID()
      const permissions = await fetchPermissionsByUser(user) // call to backend

      this.commit('permissionModule/setUserPermissions', permissions)
      this.commit('permissionModule/toggleIsFetching', false)
    },
  },
}

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

Is it safe to set content type as text/plain instead of application/json for JSON response?

I've been developing a PHP script to retrieve public JSON data, which will be accessed by JavaScript on the client side. However, I've encountered an issue with the server (LiteSpeed shared hosting) not having brotli/gzip compression enabled for ...

How can we efficiently validate specific fields within arrays and objects in express-validator by utilizing the body() method?

I have organized my field names in an array as follows: const baseFields = [ 'employeeNumber', 'firstName', 'lastName', 'trEmail', 'position' ]; These are the only input fields I need to focus on for valid ...

The callback function in jQuery does not function properly in a custom class or object

Hello, I am new to the world of programming so bear with me if this question seems basic. I am currently working on creating a simple wave effect to give the illusion of moving water. Initially, I achieved this using a straightforward jQuery function which ...

Exploring the functionalities of the execPopulate() method

I'm hitting a roadblock with using execPopulate. I've gone through the documentation, but it's just not clicking for me. Could someone clarify when exactly execPopulate() should be used after populate() and when it's unnecessary? In s ...

Unnecessary PHP code will run on its own in JavaScript

Attempting to initiate a session in PHP and assign a value to a session variable within a Javascript function on a PHP/HTML page is creating an issue. The problem arises when the PHP code inside the if statement runs automatically upon loading the page, ra ...

The React component fails to re-render upon the initial state update

Currently, I am working on a straightforward survey that requires simple Yes or No answers. The questions are stored in a separate file called QuestionsList.js: Here is the list of questions: const QuestionsList = [ "Do you believe in ghosts?", "Have you ...

JavaScript does not allow executing methods on imported arrays and maps

In my coding project, I created a map named queue in FILE 1. This map was fully built up with values and keys within FILE 1, and then exported to FILE 2 using module.exports.queue = (queue). Here is the code from FILE 1: let queue = new.Map() let key = &q ...

Using JavaScript to delete a class from an HTML element

For the past 48 hours, I've been grappling with the challenge of removing an added class from an Element. Despite scouring the internet for a solution, I haven't been able to find one. I have successfully added a class to the navigation to displ ...

Send a PHP array back to jQuery AJAX and dynamically populate a list using conditional statements

Looking to create a dynamic contact list that can be sorted using AJAX. When selecting one of the 3 menu options, a new list with updated information should be displayed. I've been doing some research but haven't come across useful information o ...

Is there a way to create a JavaScript function that relies on a successful form submission?

After attempting to modify a post on Stack Overflow, I am facing issues with my JavaScript code. As a beginner, it's possible that I overlooked something in the code causing it not to work as expected. The project I'm working on involves creatin ...

Grab the inner html content of a specific element and release it into a different element by holding down the mouse button

I am working with a grid that has a start node. My goal is to make this node a draggable object without moving the HTML element itself, as it contains important information about that particular node (such as position and state). Instead, I only want to mo ...

An issue arises with subdirectory URL parsing in Node.js, Express, and Ghost

Greetings and welcome to another discussion on the topic of serving Ghost on a subdirectory within a website! After following various threads and referencing this Github profile (https://github.com/owenscott/hapi-ghost-proxy-example/blob/master/config.js) ...

Struggling to integrate vue js into Laravel

I recently developed a character counter feature for SEO input fields using Vue JS. It functioned flawlessly on jsfiddle, however, upon integrating it with Laravel, I encountered an issue. Instead of displaying the number of characters remaining, it showed ...

What is preventing Protractor from detecting Angular on a site that has been automatically initialized with Angular?

Whenever I try to utilize browser.get() in my code, I encounter the following error: Error: Angular could not be found on the page http://localhost:5000/#/login debug=timing&saveLogs=true&displayAll=true : angular never provided resumeBootstrap A ...

The challenge with our unique PHP/JS Analytics Solution

Here's an illustration of the code snippet for Google Analytics: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'userIDhere']); _gaq.push(['_trackPageview']); _gaq.push([&apos ...

I'm looking to configure a backend like node.js/express paired with react using vite. I'm curious about the deployment process - should I rely on vite's commands or node's for this?

(PAY ATTENTION TO THE TITLE) I am new to React and eager to explore Vite.JS. While I have no knowledge of Node.js, I am determined to learn how to connect them. Can you guide me through this process? Also, when it comes to deployment, should I stick to V ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...

Avoid displaying duplicate values when using Ng-repeat in Angular JS

I'm in search of a method to prevent the display of duplicate values when using ng-repeat with Angular JS. Here is an example of my JSON list: [ { "Country":"Algeria", "Value":"200" }, { "Country":"France", "Value":"300" }, { "Country":"France", "Va ...

Angular2 forms: creating validators for fields that are interconnected

Imagine a scenario where a form allows users to input either a city name or its latitude and longitude. The requirement is that the form must validate if the city name field is filled OR if both the latitude and longitude fields are filled, with the added ...