0

I am trying to change the input type of an email field based on whether the user is on a desktop or a mobile device.

I have added a method which detects whether the user is on a mobile device or not

get isMobile() {
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
    return true;
  } else {
    return false;
  }
}

I tried to implement it in the html file like the following

<form-field :label="label">
  <span class="mandatory_field" v-if="required">*</span>
  <div v-if="!isMobile()">
   <desktop>
    <input v-bind:class="inputStyle"
      type="text"
      :id="id"
      :name="name"
      @input="$emit('input',$event.target.value)"
      :placeholder="placeholder"
      :value="value"
  />
    </desktop>
    </div>
    <div v-else>
      <mobile>
          <input v-bind:class="inputStyle"
          type="email"
          :id="id"
          :name="name"
          @input="$emit('input',$event.target.value)"
          :placeholder="placeholder"
          :value="value"
        />
      </mobile>
    </div>
  <p class="field_error">{{ error }}</p>
</form-field>

but all this does is make the email field disappear.

What is the correct way to implement this functionality in Vue.js?

1 Answer 1

3

You've defined isMobile as a getter property. This isn't necessary in Vue, and typically you would make this a computed property instead (a "computed property" is Vue-specific, see the docs).

Also you wouldn't call it like a method because it isn't a method, it's a property.

<div v-if="isMobile">Mobile</div>
<div v-else>Desktop</div>
computed: {
  isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  }
}

Technically it needn't be a computed property since it doesn't depend on any of the component's data and its value will never change, so you can instead define it as a normal data property:

data() {
  return {
    isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.