Error: vue is not defined and cannot read property '$bvModal'

It seems like this isn't scoped properly within my function. When attempting to call

this.$bvModal.show("signinModal")
in order to display the modal, I encounter the following error:

Uncaught TypeError: Cannot read property '$bvModal' of undefined

I understand that $bvModal should be scoped to the component and I'm not using any arrow functions, so I'm unsure where the problem lies. Is there a Vue-specific way to resolve this issue that I am overlooking?

<template>
  <div class="container">

    <b-modal id="signinModal" @hidden="signinUser($event)" :no-close-on-backdrop="true">
      <input id="email" v-model="email" placeholder="email">
      <input id="pass" v-model="password" placeholder="password">
    </b-modal>

    <form v-on:submit.prevent class="cube" v-if="modalShow == false">
       <div>
         <input id="title" v-model="title" placeholder="title">
       </div>

       <div>
         <textarea id="body" v-model="body" placeholder="body"></textarea>
       </div>

       <div>
         <b-button id ="postbtn" @click="addpost($event)" variant="outline-success">Publish</b-button>
       </div>    
    </form>
  </div>
</template>

<script>
const {fb,db} = require('../../fireconfig.js')

export default {
  name: 'AddPost',
  data:function(){   
    return{
        title: '',
        body: '',
        modalShow: true,
        email: '',
        password: ''
    }      
  },
  mounted(){
    this.$bvModal.show("signinModal")
  },

  methods:{
    signinUser:function(e){
      e.preventDefault()
      fb.auth()
        .signInWithEmailAndPassword(this.email, this.password)
        .catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;

          if (errorCode === 'auth/wrong-password' || errorCode === 'auth/invalid-email') {
            alert('password or email incorrect',errorCode,errorMessage);
            this.$bvModal.show("signinModal") //---------------ERROR THROWN HERE

         } else {
            console.log('user successfully authenticated')
         }
      });
    },

    addpost(event){   
      event.preventDefault()
      try {
        let data = {
           title: this.title,
           body: this.body
        }

        db.collection('articles').doc(this.title).set(data)
        console.log('uploaded data to db')
      } catch(err) {
        console.log('there was an error',err)
      }
    },
  } 
}
</script>

Answer №1

Transform your function into arrow functions within the catch block to ensure proper referencing of this with the Vue component.

signinUser:function(e){
    e.preventDefault()
   fb.auth().signInWithEmailAndPassword(this.email, this.password)
          .catch( error => {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password' || errorCode === 'auth/invalid-email') {
              alert('password or email incorrect',errorCode,errorMessage);
              this.$bvModal.show("signinModal") //---------------ERROR THROWN HERE

            } else {
              console.log('user successfully authenticated')

            }
    });
  },

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

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

Creating a function that assigns an anonymous function which in turn returns another anonymous function

Can you explain the difference in JavaScript between these two code snippets? var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { loadData(e.target.result); }; })(file); reader.readAsText(file); a ...

completing data tables and presenting them to clients

I am currently working on a website for a Nutrition specialist who requires a monthly diet regimen table with five meals daily. The doctor will be responsible for completing these tables, which will then be presented to clients. It's important that th ...

Python's Selenium encountering a NoSuchElementException with the error message "./ancestor-or-self::form"

Trying to create a Python script that allows me to input my credentials and tweet text in the Python console. The script should then log in and post a tweet using Selenium. Everything works fine, except for the final click on the Tweet button which is caus ...

Enhance tick labels in C3.js with supplementary information

I need a specific format for the tick: tick: { fit: true, multiline: false, outer: false, format: function (x) { var value = this.api.ca ...

Indeed, yet another problem with clearInterval

I could use some assistance as I am currently stuck trying to figure out why the stopTimer() function is not working correctly. Any guidance or suggestions would be highly appreciated. Thank you! http://jsfiddle.net/4Efbd/1/ var counter; function endTim ...

Is there a method to place two items in a flex container while only centering one of them?

I managed to achieve the desired effect using absolute positioning, but I know this is not the most elegant solution and it lacks re-usability. Is there a way for me to group these two elements in a flex container and center only the text? Also, I'm f ...

selecting unique elements using classes is not possible with jquery

I am experimenting with using ajax on dynamically generated html elements from django. I have tried selecting the instances by class, but for some reason, it is not working as expected. Can anyone point out my mistake here? javascript $(document).ready(fu ...

Ensure that all MySQL queries within a for loop have completed before executing the rest of a function in NodeJS

I have been attempting to execute a query in order to retrieve data from one table, then utilize that array of data to fetch information from another table before formatting and returning it as JSON. Despite my efforts, I am struggling to understand how t ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

What is the method to reach the DOM element of a different component in Angular?

My application is structured as follows: <nav></nav> <router-outlet></router-outlet> <footer></footer> Within the router-outlet, I have various components depending on the route. On some of these pages, I need to acces ...

Various ways to utilize Apollo's Query property

There are a couple of ways I've come across to utilize the new Query and Mutation props from Apollo. However, I've only been able to successfully implement one of them. First, defining the query within the Query prop directly like this: <Qu ...

The type 'AxiosResponse<IUser, any>' is not to be mistaken for an array type

I am facing a minor issue while working with axios response in my code. I have a method that fetches user profiles from an API: static async getProfileById(id: string | undefined){ const jwt = localStorage.getItem("jwt"); const response ...

Making Angular2 Templates More Efficient with Array.prototype.filter()

I have a variable named networkInterface that includes an array called services. My objective is to create a checkbox input that indicates whether a specific service_id exists within the services array of the networkInterface. An illustration of JSON `int ...

The form inputs within the modal are unresponsive to clicks

I recently began using bootstrap modals and had a separate register/login page from the index. I thought incorporating the login/register form into modals would be a good idea. However, inside the modal, all the inputs are not clickable - only accessible v ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

Embarking on your journey with the Withings API

How can I connect to my website with the Withings API? I want to send weight values to the Withings API and receive body measurement values. Where can I find the code for the Withings API? $config['withings_settings']['widgets'] = &apo ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...