Creating dynamic popovers using vue.js and bootstrap 4

I'm looking to integrate popovers from Bootstrap 4 into my Vue.js app. While I could use something like

https://www.npmjs.com/package/vue-popperjs
, I prefer to explore how to achieve this without additional libraries in order to understand the underlying principles.

To start, I have installed Popper.js using npm install --save popper.

In my webpack.config.js, I've included the following:

 plugins: [
        new WebpackNotifierPlugin(),
        new webpack.ProvidePlugin({
            _: 'lodash',
            $: 'jquery',
            jquery: 'jquery',
            'window.jQuery': 'jquery',
            jQuery: 'jquery',
            popper: 'popper'
        })
    ],

Next, I attempt to create a Vue component:

<template>
   ....
    <button type="button" class="btn btn-link" title="" data-container="body" data-toggle="popover" data-placement="bottom"  data-original-title="Connection String" aria-describedby="popover253231">
                                        Click to show 
                                    </button>
   ....
</template>
<script>
    const _ = require("lodash");
    const $ = require("jquery");

     var d = {
        data() {
           ...
        },
        created: function() {
           // Load data with $http module
        },
        updated: function() {
            $(function () {
                $('[data-toggle="popover"]').popover()
            })
        },
    };

    export default d;
</script>

The button only becomes visible once it is loaded, due to its parent element having a v-for binding on data fetched via Ajax.

I am encountering difficulties in requiring popper, as the line

$('[data-toggle="popover"]').popover()
fails to resolve (unable to find the popover() function).

Furthermore, attempting to load popper using require results in an error stating "Module parse failed: 'return' outside of function." This suggests that popper may not be compatible with the standard JS require method.

Answer №1

After encountering some challenges and experimenting with various ideas, I finally stumbled upon the solution. It turns out that the issue stemmed from my use of bootstrap installed within ASP.NET MVC as a bundle (resulting in it being added as <script src='..'/> to the page). So, here's what I did:

  1. Ran npm install --save bootstrap

  2. Inserted bootstrap: 'bootstrap' into the ProvidePlugin definition in webpack.config.js

  3. Added require("bootstrap") in my vue file

Magically, everything started functioning properly. Surprisingly, I didn't even need to include 'popper', probably because it's already included in the bootstrap package?

Although I'm still uncertain if this is the most effective way to resolve the issue.

Answer №2

Utilizing Vuejs Directive for Tooltip

const customTooltip = (el, binding) => {

const options = []

if (binding.modifiers.focus) options.push('focus')
if (binding.modifiers.hover) options.push('hover')
if (binding.modifiers.click) options.push('click')
if (!options.length) options.push('hover')

$(el).tooltip({
    animation: false,
    placement: binding.arg || 'top',
    trigger: options.join(' '),
    html: !!binding.modifiers.html,
    title: binding.value,
});}

Vue.directive('custom-tooltip', {
bind: customTooltip,
update: customTooltip,
unbind (el) { $(el).tooltip('dispose') }});

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 reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-con ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

Eliminating undesirable data coupling in Vue.js

In my application, I have an edit form where a HTTP request is made when the component is created and the response data is saved in two different variables. axios.get(this.initializeURL) .then((res) => { this.form = res.data.form th ...

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...

There seems to be a missing row in the PHP looped output of the mySQL table

I am facing an issue with a MySQL table that contains data. I am using PHP code to display this data on an HTML page and set up JavaScript variables before the page loads. However, there seems to be a problem with the loop as it is dropping or not showing ...

Navigating Three.js coordinate systems

While working with vectors in three.js, I noticed that the axes seem to be mixed up. It's confusing because Y is the vertical axis, but X and Z appear "mirrored" causing objects to only look right when viewed upside-down. How can this issue be resolv ...

Arranging various JavaScript arrays

I've been working on a script using the Haversine formula, but I'm running into an issue where it always directs me to the first location in the array, no matter how many times I switch them around. Any suggestions? var locations = new Array( ...

The jQuery.ajax converter function is not being triggered

I'm struggling with jQuery.ajax converters - my converter function isn't triggering. This is the simplified jQuery AJAX code I'm using: $.ajax({ url: "http://myurl/myservice", dataType: "JSONP", cache: false, success: ...

steps for using the push method to create a new array in JavaScript

Currently, I am attempting to create a new array that is similar to the myCourses array using the push method. However, for some reason it only seems to be logging one string at a time instead of generating a new array that mirrors the myCourses array: ...

Deactivate the action triggered by a jQuery click event

$('document').ready(function(){ //textoverflow($('.content'),100); $('span').click(function(){ //disable textoverflow function & output full text }); }); function textoverflow(ele, num){ ele.each( ...

Prevent users from selecting elements on the mobile site

Hey there! I'm currently working on preventing users from selecting items on my mobile site. While I've been successful in doing so on a regular website using the CSS class below .unselectable { -moz-user-select: -moz-none; -khtml-user-s ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

Encountering a crash issue with JMeter's Selenium Sampler while attempting to click on a button with the Phantom

After building a JMeter Project, I have been utilizing the WebDriver Sampler (Selenium) to monitor response times during interactions with a particular feature on a webpage. To test my project, I have experimented with both Firefox and Chrome Driver confi ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

Issues with removing options from Autocomplete persist in React MaterialUI

Currently navigating the world of ReactJS and experimenting with Material UI's Autocomplete component. The challenge lies in managing a complex data structure where options are dynamically generated based on user selections, but removing previously se ...

Functionality of Ajax: Data fields containing numerous values

I'm confused about the data fields in the ajax function. Typically, the syntax for an ajax function looks something like this: $.ajax({ url: "/aaa/bbb/ccc", method: "SomeMethod", data: someData, success: function (res ...

Encountering issues with installing @vue/cli on Linux Ubuntu

Currently facing an issue while attempting to install the Vue CLI on Ubuntu (WSL). After running both yarn add global @vue/cli and npm install @vue/cli --global, it seems like the commands were successful. However, upon checking the version using vue --v ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...