Tips on transferring a variable from a JavaScript file to a .vue file

Hello, I am new to using Vue.js and I am currently integrating Firebase for authentication in my project. Below is the Firebase code that I have separated into a different JavaScript file. This file contains all the mutations, states, actions, and getters which are then imported into various components.

import firebase from "firebase/app";
import "firebase/auth";

export default {
  state: {
    loggedInUser:
      localStorage.getItem("userInfo") != null
        ? JSON.parse(localStorage.getItem("userInfo"))
        : null,
    loading: false,
    error: null
  },
  getters: {
    loggedInUser: (state) => state.loggedInUser,
    loading: (state) => state.loading,
    error: (state) => state.error
  },
  mutations: {
    setUser(state, data) {
      state.loggedInUser = data;
      state.loading = false;
      state.error = null;
    },
    setLogout(state) {
      state.loggedInUser = null;
      state.loading = false;
      state.error = null;
    },
    setLoading(state, data) {
      state.loading = data;
      state.error = null;
    },
    setError(state, data) {
      state.error = data;
      state.loggedInUser = null;
      state.loading = false;
    },
    clearError(state) {
      state.error = null;
    }
  },
  actions: {
    login({ commit }, data) {
      commit("clearError");
      commit("setLoading", true);
      firebase
        .auth()
        .signInWithEmailAndPassword(data.email, data.password)
        .then((user) => {
          const newUser = { uid: user.user.uid };
          localStorage.setItem("userInfo", JSON.stringify(newUser));
          commit("setUser", { uid: user.user.uid });
          console.log("userInfo");
        })
        .catch(function (error) {
          localStorage.removeItem("userInfo");
          commit("setError", error);
        });

      firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
          let email = user.email;
        } else {
          // User is signed out.
        }
      });
    },
    signUserUp({ commit }, data) {
      commit("setLoading", true);
      commit("clearError");
      firebase
        .auth()
        .createUserWithEmailAndPassword(data.email, data.password)
        .then((user) => {
          commit("setLoading", false);

          const newUser = {
            uid: user.user.uid
          };
          console.log(newUser);
          localStorage.setItem("userInfo", JSON.stringify(newUser));
          commit("setUser", newUser);

        })
        .catch((error) => {
          commit("setLoading", false);
          commit("setError", error);
          localStorage.removeItem("userInfo");
          console.log(error);
        });
    },
    signOut({ commit }) {
      firebase
        .auth()
        .signOut()
        .then(
          () => {
            localStorage.removeItem("userInfo");
            commit("setLogout");
          },
          (_error) => {}
        );
    }
  }
};

I am importing it into the component like this:

import { mapGetters, mapActions, mapState } from "vuex";
export default {
  components: {},
  data() {
    return {
      email: ""
    };
  },
  computed: {
    ...mapGetters(["getSideBarToggleProperties"]),
    ...mapState(["loggedInUser"])
  },
  methods: {
    ...mapActions(["signOut", "login"]),

    getLogin() {
      this.login({ email: this.email });   
    },
  

Then I call the method 'getLogin' using @click to display like this:

<a class="dropdown-item" id="testing">{{loggedInUser}}</a>

Answer №1

To utilize the email addresses stored in the JS file, simply extract them and import into your Vue component within the script tag for easy access.

Answer №2

Consider this method:

// script.js file
const dataForVue = "hello from a javascript file"
export default { dataForVue }

Next, in your component:

// Greetings.vue component
<template>
  <div>
    <p>Data: {{ info.dataForVue }}</p>
    <!-- Data: hello from a javascript file -->
  </div>
</template>
<script>
  import info from './script' // Import from the specific location
  export default {
    data: () => ({ info: info })
  }
</script>

Another option is to export each variable individually and use object destructuring:

// script.js file
export const dataForVue = "hello from a javascript file"

In your component:

// Greetings.vue component
<template>
  <div>
    <p>Data: {{ dataForVue }}</p>
    <!-- Data: hello from a javascript file -->
  </div>
</template>
<script>
  import { dataForVue } from './script' // Import from the specified location
  export default {
    data: () => ({ info: dataForVue })
  }
</script>

To meet your requirements effectively, it may be beneficial to centralize the login function in Vuex and store user information there for easy access.

Additionally, creating a login component that exposes the email variable and triggers the login function can ensure reactivity and automatic updates when changes occur.

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

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

Creating effective href anchors within an iframe using the `srcdoc` attribute

While loading some HTML content in an iframe using the srcdoc attribute, I encountered an issue where following anchor tag links inside the iframe caused the entire page to load within the iframe instead of scrolling to the linked id. You can see a demons ...

Unusual patterns of shadow manipulation in ThreeJS

I am currently working on a threeJS scene with multiple spheres (multimaterial) and a directional light. The code snippet for adding the directional light is as follows: this.light = new THREE.DirectionalLight( 0xFFFFFF, 1 ); this.light.position.set( 2, ...

Is it considered a best practice to use collection.find() to retrieve all items on a master node in Mongo?

Every night at midnight, a background process retrieves all users from MongoDB and performs various checks and processes on their accounts. I have some questions regarding this process: Is it efficient in terms of performance to use the following query t ...

Is it possible for two users with distinct roles to register using a shared email address?

Is it possible for both drivers and passengers to sign up using the same email address, allowing users to log in as either a driver or passenger, or even both with one email account? I have tried to do this but received an error message stating that the e ...

What is the maximum duration we can set for the Ajax timeout?

I am facing a situation where an ajax request can take between 5-10 minutes to process on the server side. Instead of continuously polling from JavaScript to check if the request is completed, I am considering making just one ajax call and setting the tim ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

"Can you please share how to extract the values from a firebaseArray

Attempting to retrieve and log the information of each item in my firebaseArray using the following code: $scope.events = $firebaseArray(ref.child('event').orderByChild('uid').equalTo(Auth.$getAuth().uid)); $scope.events.$loaded( funct ...

The res.write function seems to be malfunctioning as it is displaying the output with HTML tags included

My endeavors in developing a web application using API's and express are met with unexpected results. The output I receive includes text mixed with HTML tags. Take a look at my code: const express = require('express'); const https = requir ...

"Emulate the social sharing capabilities of CNET with interactive share

I remember a while ago, CNET had these amazing Social Share buttons that, when clicked, would reveal a "dropdown box" with the social network share dialog. Does anyone know how they achieved that? I've searched but couldn't find any information ...

Failed attempt to register on localhost through Facebook

I have been attempting to implement the Facebook registration plugin on my localhost, but unfortunately, the registration box is not appearing as expected. Below are some screenshots for reference: Here is the code snippet I have used: <!DOCTYPE html ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

What is the best way to stop this Jquery slider from moving?

I've been struggling with this issue for what feels like forever, and it's driving me crazy! I have a slider on the homepage that I'm trying to enhance with a "click to pause" feature (and maybe even a click to resume, for good measure). I ...

Submitting a Django form seamlessly without reloading the page

Currently using Django-Angular, I am attempting to submit a form and access the data on the backend. Despite achieving this, I have noticed that the page reloads when saving the form. Is there a way to achieve this without having the page render? forms.py ...

How to Show a GIF in ASP.NET Core 3.0 When OnPost() is Invoked

I'm struggling to incorporate a GIF into my website, and after researching different sources, I've discovered that I need to utilize some Ajax and Javascript. However, I lack experience with both of these technologies. Is there anyone who could p ...

Issue: The option "filename" must be specified in order to utilize includes and extends with relative paths

Currently, I am working with Vue using the webpack template and attempting to conduct tests with Jest. Additionally, I am employing Pug for rendering the templates. However, upon running the tests, an error is encountered: [vue-jest] Error: Error: the "f ...

Error: The function 'document.getsElementsByClassName()' is not defined when evaluating 'undefined'

Actual Error TypeError: undefined is not a function (evaluating 'ActiveElem[i].hasClass('active'); HTML <div class = 'Carousel-Inner'> <div class="morningSlide active"> <img src="/Users/KO527/Sites/TarasDeli ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how ...

Tips for adjusting the header color in materialize framework?

I've been working on a web template and I'm looking to customize the color displayed in the Android browser (maybe using JS?). The default color is blue. How can I go about changing it? https://i.sstatic.net/RxLbS.jpg Appreciate any help! ...