简体   繁体   中英

Using Vue JS $refs in function

I've set up a Vue JS method which should automatically focus on the next input field if the maxlength of a field is reached. I'm trying to pass the field to focus onto through the function but it doesn't seem to work

I've tried using various setups, it seems to work if I pass the actual ref of the field, but not through the function

Method:

/**
         * Switch fields
         */
        switchToField(fieldSwitchName, fieldValue, fieldLength) {
          if (String(this.fieldValue).length >= fieldLength) {
            this.$refs.fieldSwitchName.focus();
          }
        }

HTML:

<div class="form-row">
                    <div class="form-group col">
                      <input v-on:keyup="switchToField(AppDOBMonth, formData.AppDOBDay, 2)" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" v-model="formData.AppDOBDay" name="data[ApplicationPayday][AppDOBDay]" id="AppDOBDay" v-validate="'required|numeric|max:2|min:2|max_value:31'" type="number" maxlength="2" pattern="[0-9]*" inputmode="numeric" class="form-control" placeholder="DD" @change="formData.AppDOBDay = leadingZeros(formData.AppDOBDay)">
                    </div>
                    <span class="dob-divider text-muted">/</span>
                    <div class="form-group col">
                      <input ref="AppDOBMonth" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" v-model="formData.AppDOBMonth" name="data[ApplicationPayday][AppDOBMonth]" id="AppDOBMonth" v-validate="'required|numeric|max:2|min:2|max_value:12'" type="number" maxlength="2" pattern="[0-9]*" inputmode="numeric" class="form-control" placeholder="MM" @change="formData.AppDOBMonth = leadingZeros(formData.AppDOBMonth)">
                    </div>
                  </div>

My code should be passing the value of fieldSwitchName into this.$refs.fieldSwitchName.focus(); , but it seems to be looking for a fieldSwitchName ref rather than the value being passed in.

What am I missing here?

Using the . notation you're directly pointing to the name you've supplied after the . operator on a JS object.

To dynamically assign the accessing object key, you'll need an approach like this:

this.$refs[fieldSwitchName].focus()

If switchToField is a variable, you need call $ref as array:

switchToField(fieldSwitchName, fieldValue, fieldLength) {
    if (String(this.fieldValue).length >= fieldLength) {
        this.$refs[fieldSwitchName].focus();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM