Home > Net >  login page with local storage in vue.js
login page with local storage in vue.js

Time:06-25

I want to create a login page which calls the sample login API(https://reqres.in/).

I want after user logged in it go to another page and users stay logged in if the page is refreshed but after i click the login button it doesn't go to another page and just login page refresh! and local storage is empty.

thank you for your help!

this is my login form:

<template>
  <form>
    <label>Email:</label>
    <input required v-model="email" />
    <label>Password:</label>
    <input type="password" required v-model="password" />
    <button @click="login">LOGIN</button>
  </form>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      email: "",
      password: "",
    };
  },
  methods: {
    async login() {
      let result = await axios.get(
        `https://reqres.in/api/users?email=${this.email}&password=${this.password}`
      );
      if (result.status == 200 && result.data.length > 0) {
        localStorage.setItem("userInfo", JSON.stringify(result.data));
        this.$router.push("/firstPage");
      }
      console.log(result)
    },
  },
};
</script>

CodePudding user response:

The concept of preventDefault serves to prevent the default operation of the relevant element by the browser at that moment. For example, when the a element is clicked, its default behavior is to redirect to the relevant url address. We use preventDefault to prevent this behavior.

The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

The difference between them is briefly as follows.

stopPropagation prevents the event from bubbling up the event chain.

preventDefault prevents the browser's default action on this event.

So, you just need to use stopPropagation() method.

CodePudding user response:

Try to use Named Routes: https://router.vuejs.org/guide/essentials/named-routes.html

There is a full example here: https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js

CodePudding user response:

When a <form> contains a single <button>, it's treated as the form's submit button, causing the submit event, which reloads the page.

To solve this, you can invoke Event.preventDefault on the form's submit-event with the v-on:submit directive along with the .prevent event modifier:

<form @submit.prevent>
  ⋮
</form>

demo

  • Related