Using V-model binding in Vue always resets the content of text inputs

I am facing an issue with a Text Input that is filled based on a string stored in cookies, similar to a Remember me feature. When I bind the value of the input to the cookie using :value, I am unable to type a new value even if there is no cookie being stored.

Here is the code:

<template>
    <GuestLayout class="bg-neutral">
        <Head title="Log in" />

        <div v-if="status" class="mb-4 font-medium text-sm text-white-600">
            {{ status }}
        </div>

        <form @submit.prevent="submit">
            <div>
                <InputLabel for="email" value="Email" />

                <TextInput
                    id="email"
                    type="email"
                    class="mt-1 block w-full text-neutral-focus focus:border-accent"
                    v-model="form.email"
                    :value="rememberedEmail"
                    required
                    autofocus
                    autocomplete="username"
                />

                <InputError class="mt-2" :message="form.errors.email" />
            </div>

            <div class="mt-4">
                <InputLabel for="password" value="Password" />

                <TextInput
                    id="password"
                    type="password"
                    class="mt-1 block w-full text-neutral-focus"
                    v-model="form.password"
                    required
                    autocomplete="current-password"
                />

                <InputError class="mt-2" :message="form.errors.password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <Checkbox name="remember" v-model:checked="form.remember" />
                    <span class="ml-2 text-sm text-gray-600 dark:text-gray-400"
                        >Remember me</span
                    >
                </label>
            </div>
            <div class="block mt-2">
                <Link :href="route('register')">
                    <label class="flex items-center hover:cursor-pointer">
                        <span
                            class="ml-2 text-sm text-gray-600 dark:text-gray-400"
                            >Dont have an account ? Register here</span
                        >
                    </label>
                </Link>
            </div>

            <div class="flex items-center justify-end mt-4">
                <Link
                    v-if="canResetPassword"
                    :href="route('password.request')"
                    class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800"
                >
                    Forgot your password?
                </Link>

                <PrimaryButton
                    class="ml-4"
                    :class="{ 'opacity-25': form.processing }"
                    :disabled="form.processing"
                >
                    Log in
                </PrimaryButton>
            </div>
        </form>
    </GuestLayout>
</template>

<script>
import Checkbox from "@/Components/Checkbox.vue";
import GuestLayout from "@/Layouts/GuestLayout.vue";
import InputError from "@/Components/InputError.vue";
import InputLabel from "@/Components/InputLabel.vue";
import PrimaryButton from "@/Components/PrimaryButton.vue";
import TextInput from "@/Components/TextInput.vue";
import { Head, Link, useForm } from "@inertiajs/vue3";
import { onUpdated } from "vue";
import VueCookies from "vue-cookies";
import { ref } from "vue";
import { onMounted } from "vue";

export default {
    components: {
        Head,
        Checkbox,
        GuestLayout,
        InputError,
        InputLabel,
        PrimaryButton,
        TextInput,
        Link,
    },
    props: {
        canResetPassword: Boolean,
        status: String,
        emailCookies: String,
    },
    setup() {
        // const emailCookies = ref(VueCookies.get("email"));
        let rememberedEmail = ref("");

        onMounted(() => {
            const emailCookies = ref(VueCookies.get("email"));
            if (emailCookies != null) {
                return (rememberedEmail = emailCookies);
            } else {
                return "";
            }
        });

        const form = useForm({
            email: "",
            password: "",
            remember: false,
        });
        const submit = () => {
            form.post(route("login"), {
                onFinish: () => form.reset("password"),
            });
        };
        return { form, submit, rememberedEmail };
    },
};
</script>

I have also attempted to directly detect the cookies using :value="emailCookies", but it still does not allow me to change the content of the text input. How can I make the input field editable and update it with the email stored in the cookies, if available?

Answer №1

It seems like there's a conflict between using both v-model and :value on the same input element:

setup() {
    const emailCookies = VueCookies.get("email");
    let rememberedEmail = ref(emailCookies ? emailCookies : "");

    const form = useForm({
        email: rememberedEmail.value,
        password: "",
        remember: false,
    });

    const submit = () => {
        form.post(route("login"), {
            onFinish: () => form.reset("password"),
        });
    };

    return { form, submit };
}

Also, pay attention to the usage of TextInput:

<TextInput
    id="email"
    type="email"
    class="mt-1 block w-full text-neutral-focus focus:border-accent"
    v-model="form.email"
    required
    autofocus
    autocomplete="username"
/>

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

Launching a pre-built React application

I'm facing an issue while attempting to run a pre-existing React App on my Mac locally. I have all the source files and node.js installed on my machine. Upon running npm install, I encountered a massive list of deprecations and npm ERRors that surpas ...

When the form is submitted, I am unable to record the checkbox value

Hi, I have a question regarding submitting a form to the "/delete" route when a checkbox is checked. Although I am able to submit the form successfully, I am facing an issue retrieving the checkbox value that I assigned using ejs. Below are the relevant co ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

"Utilizing datatables to efficiently submit form data to the server-side

I'm curious for those who utilize the Datatables javascript plugin, is there a way to replicate this specific example using server-side data? The current example I came across has its data hardcoded directly in the HTML. ...

execute the NPM script in the current directory

Within my package.json file for a node project, I have the following test script that utilizes the ts-node package: "scripts": { "build": "tsc", "test": "ts-node" } Executing this script from the root ...

What changes should I make to my save function in order to handle both saving and editing user information seamlessly?

My goal for the save function is to achieve two tasks: 1. Save user in table - Completed 2. Update user in table - In progress Save function snippet: var buildUser = function () { $('#save').click(function () { var newUser = {}; ...

Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead. I attempted to add another conditional statement like this: var opera ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

Ways to detect and respond to events in this particular scenario

I'm creating necessary components dynamically based on the provided CSS. This process involves iterating through a response array and generating HTML elements accordingly. for (var i = 0; i < responseinner.length; i++) { for (var k = 0; k < ...

Steps to execute a JSON file once another JSON has been successfully loaded

I'm facing a similar challenge to the one presented in this question. However, I need to load an additional JSON file after the when() method is executed. Essentially, I want to retrieve JSON data within the when() function and then use that informati ...

Maintain fullcalendar event filtering across multiple renderings

I currently have a fullcalendar that initially displays all events. I am using a select dropdown to filter the events, which works well. However, when the calendar re-renders after moving to the next month, it shows all events again. Here is my calendar in ...

Issue encountered while validating password using regex pattern?

There seems to be an issue with password validation when requiring 1 upper case, 1 lower case, 1 number, and 1 special character. methods: { validateBeforeSubmit() { this.$validator.localize('en', dict) this.$validator.validate ...

An issue has been identified in the bubble sort algorithm causing certain numerical lists to not be properly sorted when implemented in NodeJS

I am just beginning to learn about algorithms and have started with the bubble sort. I wrote my own implementation and it seems to work well most of the time when sorting a list of numbers from 1 to 100. However, occasionally there is one random number th ...

Is there a way to identify if a user originated from a Google ad and determine if this is their nth page during the session using JavaScript code?

Is there a way for me to execute specific logic when a user, who arrived at the page via a contextual advertisement, reaches a certain page during their session? How can I make this happen? ...

What benefits does registering a Vue component locally provide?

According to the Vue documentation, global registration may not always be the best option. The documentation states: Global registration is not always ideal. When using a build system like Webpack, globally registering all components can result in unnece ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

The authorization process for uploading data to Azure Data Lake Gen2

Currently, I am working on generating a Shared Access Signature (SAS) client-side within my Node.js application. The primary goal is to allow users to directly upload files to my Azure Data Lake Gen2 Blob Storage container without streaming them through th ...

Difficulties encountered when trying to load liquid using Javascript

Having trouble loading the Shopify liquid object {{product.price | json}} into JS, as it's displaying NaN with the current code on the front end. Any suggestions on how to properly pass liquid into JS? I've tried two functions but neither seem t ...

Remove a specific date entry from the database using VUE JS and Axios

I am encountering a challenge with Vuejs as I work on a To-Do list. The tasks need to be stored in a MySQL database, and I also want the ability to delete tasks. While I have succeeded in importing and creating data, I'm facing difficulty in deleting ...