Passing information between VueJs3 components

I have been coding a VueJs3 Project that includes a login system, and it's working perfectly. Now, I want to display the user's logged-in account on the homepage within a div.

The message should be: "You are logged in as:" followed by the username.

To achieve this, I need to pass the username from the login component to the home component. I've tried various methods without success so far.

By the way, all components are stored in the components folder.

Here is the code:

home.vue

    <div class="home">
        <h1>You are logged in as: {{currentusername}}</h1>
        <Maschinen/>

    </div>
</template>

<script>
    import Maschinen from '@/components/Maschinen.vue'
    import axios from 'axios'

    export default {
        name: 'Home',
        components: {
            Maschinen
        },
        data() {
            return {
                currentusername: null,
            }
        },
        async created() {
            const response = await axios.get('http://localhost:8080/user/hetwinuser', {
                headers: {
                    Authorization: 'Bearer ' + localStorage.getItem('token')
                }
            });
            this.currentusername= (response.data.username);
        }
    }
</script>



login.vue:

<template>
    <form @submit.prevent="handleSubmit">
        <h1>Login</h1>
        <!--username + pw input for login-->
        <div class="form-group">
            <label id="username">Username:</label>
            <input id="usernameinput" type="text" class="form-control" v-model="username" placeholder="Username">
        </div>
        <div>
            <label id="password">Password:</label>
            <input id="passwordinput" type="password" class="form-control" v-model="password" placeholder="Password">
        </div>
        <!--enter buttons-->
        <button class="enter">Enter</button>
        <router-link to="/register" id="goToRegister" tag="button">Register</router-link>
    </form>
</template>

<script>
    import axios from 'axios';

    export default {
        name: "Login",
        data: () => {
            return {
                username: '',
                password: ''
            }
        },
        methods: {
            async handleSubmit() {//executed when enter button is pressed
                const data = {
                    username: this.username,
                    password: this.password
                };
                axios.post('http://localhost:8080/authenticate', data) //post the username + pw and will receive the token in exchange
                    .then(
                        res => {
                            localStorage.setItem('token', res.data.jwt);
                            localStorage.setItem('currentusername', this.username);
                            //console.log(localStorage.getItem('token'));
                        }
                    ).catch(
                    err => {
                        console.log(err)
                    }
                );

            }
        },

    }
</script>

Answer №1

login credentials

Add it in store.js under the state module, then access it wherever needed

Access it using "this.$store.state.loginCredentials"

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

What is the best way to change the state of an Object?

I need to dynamically adjust the internalstatus based on the values of externalValues. If valueOne is true, then I want statusOne to be true. Similarly, if valueTwo is true, I want statusTwo to be true and statusOne to be false. const externalValues = { v ...

What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel. Incorporating Google APIs dependencies required me to obtain a Cli ...

Can you use an ajax post to search for a boolean in MongoDB without converting on the server side?

I am facing an issue with my mongo collection that has documents containing a boolean field: { name : "Tom", active : true } { name : "Jerry", active : false } In my application's client side, there is an element that triggers an AJAX po ...

Adjust the size of a div element dynamically to maintain the aspect ratio of a background image while keeping the

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to display images of varying sizes, including both portrait and landscape pictures. These images are displayed as background-image properties of the div. By default, the slider has a fixed ...

What is the best way to create a reusable component for a Material-UI Snackbar?

Having trouble getting my Alert component to display a message that says "Successfully submitted" in the parent component. The message doesn't seem to be showing up. AlertComponent import React, { useState } from "react"; import { Snackbar, Alert } f ...

Getting the value of dynamically generated buttons when they are clicked in PHP - a simple guide

In my PHP code, I have successfully created dynamic buttons. However, I am facing an issue where I need to retrieve the value of a specific button when it is clicked, and populate all the information in a form. Below is the code snippet for handling the b ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

Loading events for a fullCalendar in node.js using the jade library

I successfully integrated fullCalendar into my nodeJS application using jade and Express, and I have managed to load the calendar. Within the jade file, I pass an array containing events information. How can I display these events on the calendar within th ...

Ways to transform an Array into an object

I had the idea to create a personalized dictionary for customers by utilizing the reduce function. Currently, I am achieving this using the forEach method. const customers = [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: ' ...

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Pressing a sequence of buttons to meet a requirement using JavaScript

Currently, I have a set of four buttons that trigger an alert message when all of them are clicked. However, I am looking to modify this behavior so that the alert is displayed only when specific combinations of buttons are pressed, such as button1 and b ...

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

When creating a dynamically generated class name, the class will not display any arbitrary values

I have encountered a strange issue: I am trying to dynamically populate the content of an after: pseudo element within a computed value. What's interesting is that it works fine if the key is a string literal before returning the object, but not if t ...

Decline the input according to the percentage

After experimenting with the script, I discovered that it did not perform as expected (even though it works on Google Webapp's script HTML form). My goal is to invalidate an input if the Downpayment is less than 30% or more than 100% of the Price, in ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

simulating the behavior of setInterval within the created hook in vue.js

I've been attempting to simulate a setInterval function within my created hook, but no matter what I try, the function doesn't seem to be triggered. I have experimented with using jest.useFakeTimers and in each test, I would utilize jest.advanceT ...

Pulling information from a database query to store it within a JavaScript variable

Using Ajax/JQuery, I successfully send the variable ($name) from page1.php to page2.php without refreshing the page. When the submit button is clicked, it sends me the var $name effectively. Additionally, in my JavaScript library for charts (AmCharts), the ...

Submitting form based on HTML select input issue

I am facing an issue with a select form where the value resets to "10" every time I send the form. Is there a way to keep the selected option, for example "20", after submitting the form? Below is the code snippet: <form method='get' name=&a ...

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...