Having trouble using a setTimeout() callback to display a Bootstrap Vue modal programmatically

I am currently working on a Vue CLI application (using the Webpack template) that utilizes Bootstrap Vue for displaying modal windows. In my Vue component's mounted() hook, I am attempting to programmatically show the modal by referencing the Bootstrap Vue documentation.

<script>
export default {
  name: 'ButtonComponent',

  mounted() {
    const showModal = sessionStorage.getItem('showModal');
    if (showModal === 'yes') this.$refs.myModal.show();
  }
}
</script>

The above code functions as expected. However, when I introduce a setTimeout() function like so:

<script>
export default {
  name: 'ButtonComponent',

  mounted() {
    const showModal = sessionStorage.getItem('showModal');
    if (showModal === 'yes') setTimeout(() => this.$refs.myModal.show(), 3500);
  }
}
</script>

For some reason, the modal does not appear after 3.5 seconds as intended. Although the timeout itself works, indicated by using console.log(), it seems like the Vue JS instance may not be accessible within the timer. I have attempted declaring a variable such as const self = this; and using it in the timeout, but unfortunately, that did not resolve the issue either. Can anyone provide insights on what might be causing this behavior?

Answer №1

From a syntactical perspective, everything seems to be correct. When utilizing arrow functions, the keyword this is essentially bound to the context in which it was initially invoked. In this scenario, this within the setTimeout function refers to the Vue instances. To verify if your $ref exists, consider incorporating multiple console.log statements like the following:

setTimeout(() => {
  console.log(this); // the Vue instances
  console.log(this.$refs); // the $refs
  console.log(this.$refs.myModal); // the modal $ref
}, 3500)

Performing these checks can help confirm whether or not your myModal component has been properly binded at that moment.

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

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

I encountered a "TypeError: Unable to access property 'name' of undefined" error when attempting to export a redux reducer

UPDATE: I encountered an issue where the namePlaceholder constant was returning undefined even though I was dispatching actions correctly. When attempting to export my selector function, I received an error: Here is the component code: import React, { ...

Effortless login authentication using Disqus through Google or Facebook tokens

I have set up my website to allow users to authenticate through Google and Facebook using passport, which uses the OAuth 2.0 API. Additionally, I am utilizing Disqus to manage the comments system on my site. However, I am running into a problem where user ...

Tips for establishing and connecting numerous connections among current nodes using the same criteria

While browsing StackOverflow, I came across similar questions. However, I believe this one has a unique twist. The main issue at hand is: How can I establish multiple relationships between existing nodes? I have the following code snippet: session . ...

Shuffling arrays with JavaScript and jQuery for a touch of randomness

Looking to add some variability to your font choices? I've got an idea for you! How about randomizing three arrays for fonts, font size, and font weight? Then, we can display the results of these arrays in a div with the class name "randomFont." Each ...

Ignoring the incremented value in a jQuery function

I have been struggling to resolve this issue for quite some time now, and unfortunately, my lack of proficiency in javascript is hindering me. Here's a jfiddle with an interesting jquery code snippet that I came across: [html] <button id="addPro ...

Using ServiceWorker with React and Typescript

If you are working on a javascript-based React project, adding a Service Worker is simply a matter of updating serviceWorker.unregister() to serviceWorker.register() in index.jsx. Here is an example project structure: - src |- index.jsx |- serviceWo ...

Challenges experienced during the process of uploading a website to the server

I seem to have encountered an issue where the Navigation background image is missing after uploading my website onto the server. Surprisingly, everything else seems to be working perfectly. What could possibly be the cause of this discrepancy? navbar-de ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

Vuex 3: The State Remains Unknown

software versions: "vue": "2.4.2", "vue-router": "2.7.0", "vuex": "3.0.1" I'm working on simulating a basic login feature with two input fields that will eventually utilize JWT for authenticated logins. However, I'm encountering an issue w ...

What is the best way to choose a specific row with Enzyme?

We have chosen Jest for doing UI Test-Driven Development on our React application. Our component rendering structure looks like this: <Div> <Row> </Row> <ROW> <Row> <ROW> <Link> <Link> ...

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

Is it necessary for React components to be organized in a hierarchy?

In all my years, I've been told that React components should follow a tree hierarchy so that parent components can manage state and pass it down to their children. But is this truly necessary? The guiding principle of React states that "React has bee ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

Enzyme locates and chooses the initial occurrence of an element

I am attempting to simulate a click on the initial box out of three. My React script appears as follows: const Boxes = (props) => { return ( <div className="container"> <div onClick={props.showMessage} className="box">One& ...

Is there a way to update a field or submit a form without having to redirect or refresh the page?

I am struggling to find the right solution for updating just one field in my database called Flag, which is a Boolean field. I have tried using ajax/JQuery, but it only works for the first item in the list and stops working for subsequent items. The ID and ...

If the URL matches a specific path, then append a parameter

I've created a script that adds a parameter to a URL based on specific subfolders. For example, if the URL contains /de, it will add ?_sft_language=german. However, I'm encountering an issue where the code is running multiple times instead of jus ...

The material-ui library always registers Event.ctrlKey as true

When using the Table Component from the material-ui library, I encountered an issue with the multiSelectable feature. Setting the value of multiSelectable to true allows for multiple selections, but the behavior is not what I expected. By default, the sel ...

Issues with routeparams are preventing ng-repeat from functioning properly, without any response or resolution

For my shoppingCart project, I am working on dynamically bringing data into views. I am using routeParams in template.html but facing an issue. The data is arriving normally as checked via ng-href="#/store/{{something.name}}/{{ child.name }}" but it isn&ap ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...