Categories
Vue Answers

How to Display Different Content for Mobile Browsers in Vue.js Apps?

Spread the love

Sometimes, we want to display different content for mobile browsers in Vue.js apps.

In this article, we’ll look at how to display different content for mobile browsers in Vue.js apps.

Display Different Content for Mobile Browsers in Vue.js Apps

We can display different content for mobile browsers in Vue.js apps by checking the user agent of the browser to determine whether the browser is a mobile browser and display the content accordingly.

For instance, we can write:

<template>
  <div id="app">
    <div v-if="!isMobile()">desktop</div>
    <div v-else>mobile</div>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    isMobile() {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        navigator.userAgent
      );
    },
  },
};
</script>

We added the isMobile method which checks the navigator.userAgent string property to see if it has any of the keywords for mobile browsers.

Then in the template, we call the isMobile method in the v-if directive to see if the browser isn’t mobile.

If it isn’t, then we display ‘desktop’, otherwise, we display ‘mobile’ with the v-else directive.

Also, we can check the width of the screen and display content accordingly.

For example, we can write:

<template>
  <div id="app">
    <div v-if="!isMobile">desktop</div>
    <div v-else>mobile</div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      isMobile: true,
    };
  },
  mounted() {
    this.onResize();
    window.addEventListener("resize", this.onResize, { passive: true });
  },
  methods: {
    onResize() {
      this.isMobile = window.innerWidth < 600;
    },
  },
  beforeDestroy() {
    if (typeof window !== "undefined") {
      window.removeEventListener("resize", this.onResize, { passive: true });
    }
  },
};
</script>

We call addEventListener with 'resize' to listen to the resize event.

If it’s triggered, then we run the onResize method to set the isMobile reactive property according to the screen size.

If window.innerWidth is less than 600, then we set it to true .

Otherwise, we set it to false .

In the beforeDestroy hook, we call window.removeEventListener to remove the resize event listener.

Conclusion

We can display different content for mobile browsers in Vue.js apps by checking the user agent of the browser to determine whether the browser is a mobile browser and display the content accordingly.

Also, we can check the width of the screen and display content accordingly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *