Using Vue.js with Vue Router to handle login functionality and automatically refreshing data

I am currently working on a Vue.js application and have successfully implemented authentication functionality, including checking if the user is logged in.

After logging in, I want to fetch some data and store it in localStorage. However, I have encountered an issue where the data stored in localStorage is not reactive. This means that when I land on the dashboard after a successful login, the data (such as userdata) is not accessible unless I click on a route link first.

So my question is, how can I "emulate" or trigger a soft refresh similar to clicking on a link and changing routes upon login?

Below is my login component code, with the localStorage data being set in the auth script.

<template>
  <div id="loginInput">
      <div class="login-box">
        <div class="login-header">
            <img src="../assets/images/Logotype.png">
        </div>
        <div class="login-body">
            <div v-show="!forgot">
                <h1>Log in</h1>
                <form @submit.prevent="login" autocomplete="off"> 
                    <input class="form-control" placeholder="Email Address" type="email" v-model="email" />
                    <input class="form-control" placeholder="Password" type="password" v-model="pass" />
                    <button class="btn btn-block" type="submit">Login</button>
                    <p v-if="error" class="error">Bad login information</p>
                </form>
            </div>
            <div v-show="forgot">
                <h1>Forgott password</h1>
                <input class="form-control" placeholder="Email Address" type="text" v-model="emailForgot" />
                <button class="btn btn-block" type="button">Reset password</button>
            </div>
        </div>
        <div class="login-footer">
            <a href="#" v-show="!forgot" v-on:click.prevent="forgot = true">Forgot password?</a>
            <a href="#" v-show="forgot" v-on:click.prevent="forgot = false">Login</a>
        </div>
      </div>
  </div>
</template>

<script>
    import auth from '@/assets/js/auth'
    export default {
        data() {
            return {
                email: '',
                pass: '',
                emailForgot: '',
                forgot: false,
                error: false,
            }
        },
        methods: {
            login () {

                auth.login(this.email, this.pass, loggedIn => {
                if (!loggedIn) {
                    this.error = true
                } else {
                    this.$router.replace(this.$route.query.redirect || '/')
                }
                })
            }
        }
    }
</script>
<style>
  .error {
    color: red;
  }
</style>

Answer №1

I successfully implemented Vuex into my application, providing a centralized store for data accessible to all components.

Utilizing Vuex allowed me to create reactive localStorage functionality, enabling seamless updates across all components.

Visit this link for more information on utilizing local storage with Vuex in Vue.js

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

Issue: Encounter of an unexpected token (Please ensure that plugins are installed to import files that are not JavaScript) while using the rollup vue package

I am working on creating a Vue component library, but I encountered an error with my type checking. I attempted to update TypeScript as mentioned here, but it did not resolve the issue. Here is a snippet of my code and `package.json` file. My component cod ...

What is the best way to utilize a basic jQuery hide/show function to display everything before hiding it?

I have a dropdown menu where selecting an option will display a specific section based on the matching value and class, while hiding all other sections. How can I set it up so that before any selection is made, all sections are displayed and only hide afte ...

Is it possible to utilize jQuery to insert a chosen form into a table?

Here is the code example I am working with: <label for="">Select Ticker: </label> <select class="form-control" style="display: inline" id='selected'> {% for p in tickers %} <option value="{{ p.tick ...

Ensure that the input remains below ten

My goal here is to ensure that the value in an input element is a non-zero digit (0<x<=9). Here's the HTML tag I'm using: <input type="number" class="cell"> I've experimented with various JavaScript solutions, but so far none h ...

Switching an array with a single string in MongoDB

I'm facing an issue with grouping data in mongoDB and wondering if there's a way to transform an array into a string. The objects included in $lookup are currently displayed in an array format, but I need them in a single string. Here is my code ...

Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue: <div id="banner-container" class="row"> <div class="col-xs-12"> <div class="card mb-2"> <div ...

Preserving form data using JavaScript exclusively upon submission

Hey there! I'm facing a little issue with a Form that has multiple checkboxes and a piece of JavaScript code designed to save the state of each checkbox when the user hits submit. My problem is that, currently, the checkbox state is being saved even i ...

What is preventing Facebook from merging its CSS/JS files together?

I wonder about the reasoning behind Facebook developers' decision not to consolidate their scripts and stylesheets into single files, opting instead to load them on demand through their CDN. Considering the complexity of Facebook as an application, I ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

A different approach to calling JavaScript functions

I have a method that populates an array. I would like to utilize it in this manner: arrayname.fill("First Array"); And not like this: arrayname = fill("First Array"); What approach should I take? function fillArray(name) { let newArray = ...

Uh oh: encountered an unexpected token 'export' in node_modulesexpoAppEntry.js

I'm encountering a challenge with my Expo project. While attempting to launch my app using yarn start, I'm running into this error: Android Bundling failed 449ms error: node_modules\expo\AppEntry.js: Unexpected token 'export&apo ...

Tips for setting a blank date field as the default value in a ui-datepicker in Vue.js

I'm working with a ui-datepicker in vue.js and I need to have the field empty or blank by default. <ui-datepicker label="Date" v-model="searchDate" :custom-formatter="picker9Formatter" :lang="picker12Lang"> </ui-datepicke ...

Refresh the vuex store values in real-time on the displayed page without the need

I am currently working on displaying variables from my backend that update automatically. To achieve this, I am utilizing Vuex store and nuxt.config.js for transferring the variables. API calls are used to modify the variables in the backend. However, I am ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

What is the best way to combine PHP and HTML within a JavaScript script?

I'm facing a challenge with integrating dynamically added elements and a populated drop down on my form. Is there a way to combine the two seamlessly? Below is the code snippet I'm using for dynamically adding and removing elements: $(docu ...

The element '<selector>' is unrecognized and cannot be found

Before I proceed with my query: I have gone through similar questions with the same title and followed the given advice, but none of it has worked for me. Therefore, I have decided to create a new question. In my Angular project, I have one module and mul ...

What are some ways to incorporate texture into objects using three.js?

Having trouble adding texture to my central sphere (earth) without the object disappearing. Can someone provide guidance on where I might be making a mistake? Your help is appreciated. For reference, here is the link to my jsbin http://jsbin.com/cabape/edi ...

Saving a collection of React.js components in JavaScript to a specific location or storage for future use

Important Note: I am unable to utilize the Node FS module as my knowledge about npm and fs is limited. In my current project, I am developing a simple game where users can interact by clicking a button to display an image of a 'duck' on screen. ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

Steps for creating a basic table filter using jQuery

What is an efficient way to create a basic table filter using jQuery without pagination requirements? I want to retrieve data from a database and display it as a list. I would like to avoid using plugins and instead opt for concise code snippets. For ...