user6248190
user6248190

Reputation: 1269

conditional rendering using vue.js

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?

Upvotes: 0

Views: 413

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

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)
  }
}

Upvotes: 3

Related Questions