Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js.

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import VueTailwind from "vue-tailwind";
import { FirebaseApp } from "@/firebase/firebase";
//Style
import "@/assets/styles/app.css";
import settings from "@/assets/styles/Tailwind.js";

FirebaseApp.auth().onAuthStateChanged((user)=>{
  Vue.prototype.$user = user;
})

//Vue
Vue.config.productionTip = false;
Vue.use(VueTailwind, settings);
Vue.prototype.$firebase = FirebaseApp;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

within a Login component:

<script>
export default {
  name: "Login",
  mounted: function () {
    this.submit();
  },
  methods: {
    submit() {
      let login = document.getElementById("login");     
      login.addEventListener(
        "submit",
        function (event) {
          event.preventDefault();
          const email = login.email.value;
          const password = login.password.value;
          this.$firebase
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then((user) => {
              console.log(user)
              this.$router.replace('/')
            })
            .catch((error) => {
              console.log(error);
            });
        },
        true
      );
    },
  },
};
</script>

However, I encountered a

TypeError: Cannot read property 'auth' of undefined
, along with issues accessing this.$router. Moving the object instantiation outside of the .addEventListener provided access through let signIn, but that's not the desired behavior. Instead, I want to automatically route between login and dashboard on onAuthStateChange by using Vue.prototype.$firebase instead of local instantiation.

<script>
export default {
  name: "Login",
  mounted: function () {
    this.submit();
  },
  methods: {
    submit() {
      let login = document.getElementById("login");
      let signIn = this.$FirebaseApp;
      let onLogin = this.$router;
      login.addEventListener(
        "submit",
        function (event) {
          event.preventDefault();
          const email = login.email.value;
          const password = login.password.value;
          signIn
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then((user) => {
              console.log(user)
              onLogin.replace('/')
            })
            .catch((error) => {
              console.log(error);
            });
        },
        true
      );
    },
  },
};
</script>

What is the correct way to access Vue.prototype.$firebase and why does it have such scope limitations?

Answer №1

It's best to avoid utilizing function() within component callbacks and instead opt for arrow functions.

The function creates its own unique this context, causing this to no longer reference the component. On the other hand, arrow functions leverage the surrounding this context:

login.addEventListener(
  "submit",
  (event) => {   // Changed to an arrow function
  ...            // Now, you can access `this.$firebase`
  },
  true
);

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

Handlebars does not support loading data into variables using Express

My NodeJS/Express application utilizes Handlebars for templates, and everything works smoothly except when attempting to display data retrieved from an Express API. The data is successfully fetched and can be viewed in the Chrome debugger. In the problem ...

Unable to transform object into a primitive value using imported JSON data

I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and iterating through JSON data store ...

Create unique identifiers for the TD elements of Viz.js that will be displayed within the SVG elements

Below is the DOT code snippet in Viz.js that I am working with: digraph G { node [fontname = "font-awesome"]; 17 [id=17, shape="hexagon", label=<<TABLE BORDER="0"> <TR><TD>undefined</TD></TR> <TR><TD>[47-56]< ...

Showing child elements within a div using AngularJS

I am eager to create a straightforward AngularJS website that will showcase an initially hidden HTML element along with all of its children. Below is the HTML structure snippet I plan to use: <div class="hiddenStuff"> <h3>Game Over</h3&g ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

Tips for maintaining position when refreshing a web page within a scrolling table

Recently, I came across a helpful tutorial on how to create a table with a fixed header and scrollable body. You can find it here. While the tutorial worked perfectly for me, I encountered an issue when trying to refresh the webpage and maintain my positio ...

Display only distinct items in a v-for loop in Vue.js

I am attempting to show icons based on specific v-for and v-if conditions. However, the icons are appearing multiple times when I only want them to display once. I attempted using v-if = 'index === 0', but this did not resolve the issue. <di ...

Strategies for sending checkbox data to MySQL via AJAX and jQuery

Looking for assistance on passing values of multiple checkboxes to MySQL using arrays with AJAX (jQuery). I've written two separate code snippets, is there someone who can help me merge them? $(document).ready(function(){ var selected = []; $(&apo ...

The URL provided for the Ajax HTTP request is not accurate

Consider the following JavaScript code: <script type="text/javascript" charset="utf-8> function goForLogin() { var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","/account/login",true); xmlhttp.s ...

Embeddable javascript code can be enhanced by incorporating references into the header

I have developed a basic calculator application using HTML, JavaScript, JQuery, and CSS. My intention is to allow others to embed this calculator app on their own web pages by utilizing a file named generate.js. Within this file, there are several documen ...

Trouble receiving Ajax response

Below is the code snippet I am working on: function f(){ var value = ""; var request1 = $.ajax({ url : '/a', type: "GET" }); var request2 = $.ajax({ url: '/b', type: ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

Glistening tabPanel and Analytics by Google

I recently completed a comprehensive tutorial here that delves into the intricacies of Google Analytics. Despite grasping the concepts explained in the tutorial, my understanding of jQuery remains at ground zero. In my ShinyApp, I utilize multiple tabPanel ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

"Upload a text file and create a JavaScript variable that contains the text within it

I am currently developing a library and I need to add a feature that reads the contents of a text file. Currently, it only returns the path. How can I modify it to return the actual content of the file? function displayFileContent() { var file = do ...

Interface-derived properties

One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript: export interface TimeBased { start_time: Date; end_time: Date; duration_in_hours: number; } To implement this interface, I've created ...

Vue warning: Issue encountered during rendering - TypeError: Attempting to access the 'id' property of an undefined variable

As I develop my CRUD application using Laravel and VueJS, I encounter an error message when submitting the creation form: [Vue warn]: Error in render: "TypeError: Cannot read property 'id' of undefined" Below is my createUser method: export def ...

How can I modify the header size of my cards in Bootstrap-Vue?

How do I adjust the size of my card's header text? <b-card header = "We are certified data installers" md="5" class="card" bg-variant="dark" style="border-color: rgb(235, 100, 33); font-size: 30px;" ...

Avoid displaying identical items when rendering a page from JSON data

I am using ajax and json to render a page. The structure of my json is as follows: {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]}. I want to load the data using ajax only once if 'points' have duplicates in any of the ...