In this tutorial, we provide two examples to detect whether it is a mobile device or not. We use navigator.platform
and the Options
API in the first example, and in the second example, we utilize navigator.userAgent
and the Compositions API. Feel free to use the provided code, and for customized code, use the ‘Try it’ functionality.
Example 1 : Vue Get Device Information
In this example, we detect whether the user has come with a mobile browser or a desktop browser. We use ‘navigator.platform’ to get device information. In this, you can use ‘Try it’ to edit and customize the code.
Vue Detect Mobile (Options Api)
<div id="app">
<P v-if="deviceType">Device Type: {{ deviceType }}</P>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
deviceType: null,
};
},
mounted() {
this.setDeviceType();
},
methods: {
setDeviceType() {
const platform = navigator.platform.toLowerCase();
if (/(android|webos|iphone|ipad|ipod|blackberry|windows phone)/.test(platform)) {
this.deviceType = 'mobile';
} else if (/mac|win|linux/i.test(platform)) {
this.deviceType = 'desktop';
} else if (/tablet|ipad/i.test(platform)) {
this.deviceType = 'tablet';
} else {
this.deviceType = 'unknown';
}
},
},
});
</script>
Output of Vue Detect Mobile or Desktop Browser
Vue 3 Detect If Mobile (Composition Api)
<script type="module">
const {createApp,ref,onMounted} = Vue;
createApp({
setup() {
const isMobile = ref(false);
const detectMobile = () => {
isMobile.value = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
};
onMounted(() => {
detectMobile();
});
return {
isMobile,
};
}
}).mount("#app");
</script>