Home > Software design >  change data variable when passed into a method in vue
change data variable when passed into a method in vue

Time:11-09

I have the following vue component where I am changing the class of the parent row based on whether or not an input is focused

<template>
    <div class="form form--login">
        <div class="form__row" :class="{entered: emailEntered}">
            <label class="form__label" for="login-form-email">Email address</label>
            <input type="text" class="form__control form__control--textbox" name="email-address" id="login-form-email" @focus="emailEntered = true" @blur="handleBlur($event, emailEntered)">
        </div>
        <div class="form__row" :class="{entered: passwordEntered}">
            <label class="form__label" for="login-form-password">Password</label>
            <input type="password" class="form__control form__control--textbox form__control--password" name="password" id="login-form-password" @focus="passwordEntered = true" @blur="handleBlur($event, passwordEntered)">
        </div>
    </div>
</template>

<script>
    export default {
        name: 'login-form',
        data() {
            return {
                emailEntered: false,
                passwordEntered: false,
            }
        },
        methods: {
            handleBlur(e, enteredBool) {
                if (e.currentTarget.value.trim() === '') {
                    // this doesn't do anything - I can do an if else statement to change this.passwordEntered or this.emailEntered based on the name of the current target, but how do I change the value by passing it into the method?
                    enteredBool = false;  
                }
            },
        }
    }
</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

but it doesn't seem to change the variable that is passed into the method - how do I pass a data variable into the method and change it's value? Or should I be doing it in a different way? I don't really want to be doing an if else statement as I may have a form that has got a lot more inputs on and I think that would be really inefficient to maintain

I also thought that I could do something in the @bur as you can do @blur="passwordEntered = false", but I wasn't sure how to check if the field was empty or not

CodePudding user response:

In order to change the variable, you need to refer it using this

 handleBlur(e, enteredBool) {
   if (e.currentTarget.value.trim() === '') {
     this[enteredBool] = false;   //Change added
   }
 },

and the way you pass it should be like

@blur="handleBlur($event, 'emailEntered')" //Added single quotes

and

@blur="handleBlur($event, 'passwordEntered')" //Added single quotes
  • Related