Vue - Creating a custom directive to instantiate a component

I am looking to enhance security for certain actions that require authentication by displaying a popover prompt for sign in/register to unauthenticated users.

My desired implementation would be something like this:

<button require-auth>Like</button>

When an unauthenticated user clicks on the button, a popover will appear (leveraging Bootstrap Vue popover) prompting them to sign in before proceeding.

To achieve this, I have created a custom directive that listens for the click event and checks the user's authentication status. The challenge lies in how to instantiate the popover component from within the directive and display it.

Here is what I have tried so far without success:

export const Authenticated: DirectiveOptions = {
  bind (el, binding, vnode) {
    el.addEventListener('click', (event) => {
      if (store.getters['users/authenticated']) {
        return;
      }

      event.preventDefault();

      const node = document.createElement('div');

      const placement = get(binding, 'value', 'auto');
      const template = `
        <p>You must be logged in to perform this action</p>
        <div>
          <b-button block :to="{ name: 'login' }">Log In</b-button>
          <b-button block :to="{ name: 'register' }">Sign Up</b-button>
        </div>`;

      const popover = new BPopover({
        propsData: { target: el, placement },
      });

      popover.$slots.default = [template as any];
      popover.$slots.title = ['Authentication Required' as any];

      popover.$mount(node);
      popover.$emit('open');

      console.log(popover.$el)
    })
  },
};

While I understand that using a component might simplify this process, I aim to make it work with any type of button without breaking the page structure by utilizing slots and wrapping content within a div element.

How can I successfully trigger the popover in this context?

Answer №1

Within the popover content: v-if="userNotLoggedIn"

When the button is clicked: @click="verifyUserAuth"

Code for handling user authentication:

data() {
    return {
        userNotLoggedIn: false
    }
},
methods: {
    verifyUserAuth () {
        if (this.userLoggedIn) {
            // Carry out necessary actions
        } else {
            this.userNotLoggedIn = true;
        }
    }
}

Also, ensure to reset userNotLoggedIn when the popover closes or the button is interacted with.

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

Embed a variable into an HTML element without affecting the inner HTML content

I am trying to inject a specific string into an HTML tag <td anyElement="{{myString}}" >some random text here </td> My desired interpretation is as follows: <td anyElement='Some string'>some random text here </td> Howe ...

Changing the color of a div while implementing a show and hide effect in JavaScript

I have designed a checkout system with three distinct parts - shipping information, billing information, and order confirmation. These sections are all on the same page, allowing for a seamless flow during the checkout process. Once a customer completes t ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Empty dropdown list displaying no options

<script> function populateDropdown() { var dropdown = document.getElementById("ddFAge"); for(var i=1;i<=100;i++) { var newOption = new Option() newOption=document.createEle ...

Issue: [$injector:unpr] encountered while configuring routing

Looking to implement a basic authentication system for my angularjs application. The problem arises when I try to debug the app.js on line 20, and an error is displayed: Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr?p0=configPr ...

The State of NgRX Entity is encountering undefined IDs

I decided to experiment with @ngrx/entity in a simple "Todo" project, where I had only one AppModule, one reducer, and a single component. However, as I delved into it, I encountered some challenges. The actions I defined were quite basic, focusing on CRU ...

The issue of unselection not functioning properly for multiple items when using both selectable and draggable features

i need the unselection of list items to be as smooth as selectable() but without draggable() My desired outcome is similar to the following gif showcasing combined selectable and draggable functionality: https://i.stack.imgur.com/3GjTD.gif here's t ...

Prepare the data for parsing into a highcharts pie chart

I developed an application that retrieves JSON data of the top stock movers in a day from a Google spreadsheet. Using this data, I create a pie chart displaying the various movers and the number of shares sold by populating the chart through AJAX. Below i ...

What could be causing the lack of data for the current user?

I have been attempting to fetch the current user session and display the data in the view, but nothing is appearing. I even checked the database and confirmed an active session with all the necessary information. I attempted logging the user out and starti ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Tips for incorporating a div wrapper into an existing foreach loop

In my PHP script, I have a foreach loop that is iterating over data retrieved from a database. Within this loop, I have several div elements that each contain dynamic data with IDs like item1, item2, item3, and so on. There are a total of 8 items in the l ...

The latest bug fix and update in Bootstrap 4.5.2 now includes an updated version of Popper.js. Make sure to use the

Hello fellow developers, I am currently working with npm bootstrap version 4.5.2 and above. However, I am facing an issue with the compatibility of @popperjs/core. If anyone can assist me in resolving the bootstrap.js error temporarily, specifically re ...

Guide on sending an object containing translation strings from Symfony Twig to a Vue component

I am currently working with Shopware using Symfony Twig. I have a small Vue app that needs to be implemented, but I am facing an issue where I am only getting the object keys and not the values when trying to pass translated strings from the shop as text i ...

When the document exists, the findOne() method returns null

Running locally, but accessing an atlas MongoDb DB online, I have builder's data like this: [ { "_id": "5ec63e97516541c07c2b26d3", "name": "Bob" }, { "_id": "5ec64261b9be7b08cb8d7ba9", "name": "builder post test" } ] Although s ...

The React Redux Saga triggers multiple API calls in a loop

I'm encountering an issue while fetching records in redux saga. There seems to be a strange behavior where calling an action in useEffect from the class triggers multiple calls in a loop, leading to endless API requests. Could someone please point ou ...

Issue with Vue Multiselect auto-suggestion functionality

I've been utilizing the [vue-multiselect] library for my project. [1]: https://www.npmjs.com/package/vue-multiselect. Within a form, I have multiple multiselect dropdowns. The issue I'm facing is with the browser's autocomplete feature. I&a ...

A step-by-step guide on accessing and displaying local Storage JSON data in the index.html file of an Angular project, showcasing it on the

I am facing an issue with reading JSON data from localStorage in my Angular index.html file and displaying it when viewing the page source. Below is the code I have attempted: Please note that when checking the View page source, only plain HTML is being ...

Executing a function upon loading a page triggered by a submitted form

Recently on my index.php page, I implemented a form that posts data into a third-party newsletter system. After the form submission, the page reloads to index.php?mail&. Is there a way to detect when the page is loaded and determine if the form has bee ...

Implementing Vuetify in Laravel (Issue: Vuetify Initialization Error)

I am currently working with Laravel 5.8 that comes integrated with Vue JS by default, and I am looking to implement Vuetify. After following the instructions provided in the blog post https://codersdiaries.com/laravel-vuetify/, I encountered an error messa ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...