This code snippet detects the orientation of a user’s device screen (portrait or landscape) in Vue.

It is particularly useful when you want to change the layout or functionality of your web page based on the screen orientation.

Table of Contents

Code Snippet

<script>
export default {
  mounted() {
    window.addEventListener(
      "orientationchange",
      this.handleOrientationChange
    );
  },
  methods: {
    handleOrientationChange() {
      const orientation = window.screen.orientation.type
      if (orientation === "portrait-primary") {
        // portrait mode
      } else if (orientation === "landscape-primary") {
        // landscape mode
      }
    }
  }
};
</script>

Explanation:

The code adds an event listener for the 'orientationchange' event, which is fired when the orientation of the device’s screen changes.

When this event is fired, the 'handleOrientationChange' method is called.

This method checks the ‘type’ property of the 'screen.orientation' object.

If it’s 'portrait-primary', the device is in portrait mode, and any necessary actions can be taken.

If it’s ‘landscape-primary’, the device is in landscape mode, and any necessary actions can be taken.

Usage

To use this code snippet, you’ll need to have a Vue project set up.

You can add this code to any Vue component where you want to detect screen orientation changes.

Also, remember to replace the comments in the 'handleOrientationChange' method with the code to handle portrait and landscape modes as needed.

Example:

Let’s say you have a video player on your webpage, and you want it to go fullscreen when the user changes to landscape mode. Your 'handleOrientationChange' method might look like this:

handleOrientationChange() {
  const orientation = window.screen.orientation.type
  if (orientation === "portrait-primary") {
    this.exitFullscreen();
  } else if (orientation === "landscape-primary") {
    this.launchFullscreen();
  }
}

Here, 'exitFullscreen' and 'launchFullscreen' would be additional methods you’ve defined on the Vue component to handle the video player.

Conclusion:

This is a straightforward way to detect the orientation of a user’s device screen in Vue.

It’s particularly useful when you want to adapt the layout or functionality of your web page based on the screen orientation.

Remember to replace the comments in the 'handleOrientationChange' method with the actual code for handling portrait and landscape modes.