Navigating through login functionalities in a Vue.js project

I've developed a login feature using the code below for users to access the backend, which is built on Flask and utilizes flask_login.

const LoginScreen = {

    template: `
                <div>
                    <h1>Sign In</h1>
                    <form id="loginform" class="pure-form">
                        <fieldset>
                            <input type="text" name="email" placeholder="email" v-model="logindetails.email"/>
                            <input type="password" name="password" placeholder="password" v-model="logindetails.password"/>
                            <button class="pure-button pure-button-primary" v-on:click="login">Login</button>
                        </fieldset>
                    </form>
                </div>
    `,

    data: function () {
        return {
                logindetails:{}
        }
    },

    methods: {
                login: function(){
                                    axios.post('/login/',
                                        this.logindetails,
                                           {
                                             headers: {
                                                        'Content-type': 'application/json',
                                                        'Accept': 'application/json',
                                                        'X-CSRF-TOKEN': document.querySelector('#csrftoken').getAttribute('content')
                                                       }
                                           }
                                          ).then(response => { this.logindetails = {};
                                                               this.$router.push({path: '/'});
                                                             }
                                                )
                                           .catch(function (error) {
                                                              console.log(error);
                                                            });
                                    }
            }
};

The functionality appears to be functioning properly (although there are occasional instances where it prompts re-login without cause), but I am encountering an issue where the form details are being added to the URL query string after submission (example).

Could someone please guide me on what might be incorrect in my implementation or direct me towards a better approach for implementing user logins?

Thank you in advance.

Answer №1

For a different approach, check out the Vue v-on event modifiers documentation to make changes to how elements behave by default.

If you want to apply this in your situation, you can try:

<button @click.prevent="login">Login</button>

Alternatively, for a form tag (make sure your submit button is of type "submit"):

<form @submit.prevent="login">

Answer №2

When it comes to

taking the form submissions and adding them to the URL query string
, this happens because clicking on a button also triggers the submit action of the form.

Traditionally, HTML forms send their values to the server for processing.

However, in JavaScript frameworks like Vue or React, form values are often submitted via AJAX without needing to refresh the page. Therefore, using the <form> element may not be necessary in these cases.

If you find yourself in this situation, there are a couple of things you could consider:

  1. Removing the <form> element altogether should still work correctly.
  2. Handling the form submission event manually. For example:

<form @submit="handleSubmit($event)">

methods: {
    handleSubmit:(e) =>{
      e.preventDefault();
    }
}

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

Challenges in Implementing Jquery Autocomplete with Spring Framework Version 2.5.6

I am facing an issue with displaying an autocomplete list using JQuery and Spring 2.5.6. I am able to retrieve the JSON data on the front end, but I am unable to display it properly. $(function() { $("#globalSearch").autocomplete({ source: fun ...

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

What is the best way to allocate mapState data in a list?

Currently, I'm tackling an apex bar chart project where I need to assign a list of mapState data into the apex series data. Here's the code snippet: <script> import { mapState } from 'vuex'; export default { data: () => ({ ...

Leveraging AJAX for database variable checks and PHP and JavaScript to redirect to specific pages based on the results

I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...

What is the best way to dynamically update a progress bar in Vue.js based on changes in JSON data without needing

I am currently working on a Bootstrap dashboard page to track the status of my Python application running on a server. The Python app updates a data.json file on the server side when it reaches a certain status, while Vue.js handles content creation on th ...

Search box that utilizes a WordPress AJAX autocomplete feature

Looking to create a search box with ajax that displays instant post titles, but struggling to find helpful information online. Can someone offer assistance? I understand that I need to use the following code to retrieve results in wpdb: $words = $wpdb-&g ...

Refreshing SQL Server data using an HTML form

In the table below: <table id="skuTable" role="grid"> <thead> <th class="skuRow">Order</th> <th>Fab. Date</th> <th class="skuRow">Norder</th> <th>Color</th> ...

What are some strategies for navigating the constraint of having multiple root elements in Vue.js?

Seeking assistance from the experts here to solve this particular issue. I have a dataset that looks like this: [ { title: 'Header', children: [ { title: 'Paragraph', children: [], }, ], }, ...

Unable to retrieve DateTime.Now as a string within a Razor view

I am trying to retrieve the current time in a Razor View and utilize it in JavaScript, as demonstrated below: @{ string fileName = "Score_List_" + DateTime.Now.ToShortDateString(); } <script> // assigning C# variable to JavaScript variabl ...

How to run 'npm' scripts externally in package.json on Windows?

In the world of development, running arbitrary commands using npm run is a common practice. This involves adding a scripts hash to your package.json: "scripts": { "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js" } To exec ...

Selenium: The function moveToElement is not valid for the driver.actions() method

After creating all my tests using Selenium IDE, I decided to export them to JavaScript Mocha for running in travis. While the tests run smoothly in Selenium IDE and can be exported, I encountered an issue when trying to run them which resulted in the erro ...

Searching for information in one array using a loop with another array (MongoDB and JavaScript)

I have two arrays that need to be compared for matching elements. let firstArray = [1, 2, 3] let secondArray = [{id:1}, {id:1}, {id:3}] I am trying to create a new array containing objects with the same id. Despite trying different approaches, I am unabl ...

Can you provide the proper syntax for the Jquery done() function?

I'm currently dealing with the code below: However, I encountered an error on line 6: Uncaught SyntaxError: Unexpected token { Even after reviewing the documentation for the done() function, I'm unable to identify my mistake here. ...

When calling mongoose.connect(), the initial parameter must be a String but it was found to be

I am facing issues while setting up the test database for testing purposes. The connection error shown when trying to connect to MongoDB using Mongoose is: throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + ^ MongooseEr ...

Implement intro.js on a bootstrap dropdown component

I'm having difficulty using intro.js with dropdown elements. I came across a similar question on this topic with no answer: IntroJS Bootstrap Menu doesnt work If you want to see the error in action, follow these steps: Click on "Aide" (The green bu ...

Using spline3D in combination with Vue or Nuxt: A beginner's guide

I recently started experimenting with Vue and wanted to create an interactive site using spline 3D. While there is a library for reactjs in splinetool, I couldn't find one for Vue. I attempted to import @splinetool/runtime and export it, but the 3D sc ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

What is the method to determine if a date is larger or smaller than another using Javascript?

Using the inputText function retrieves the value entered in the textbox, while the hidden field value returns the current value. This is my current code snippet: if (inputText.value.length != 0) { if (inputText.value < document.getElementById(&apo ...

relocating an SVG graphic within a designated area on a webpage

I have been working on a project where I allow users to place text elements onto an SVG and then make them draggable for repositioning. While I have successfully implemented the placement and editing of the text element, I am facing challenges when trying ...

Automatically assign a name as an alt attribute

Is there a way in this script to include an alt tag with the value "NikeAir 32" in the given example? <script> function test_options_rendered(){ $('.test_option_value').each(function(){ if( !$(this).parent().hasCla ...