Blog>
Snippets

Handling Mobile Sensors and Orientation Changes

Demonstrate listening to device orientation events in Vue 3 components, and adjusting UI components accordingly for an adaptive mobile experience.
app.component('adaptive-component', {
  data() {
    return {
      // Initial orientation state
      isPortrait: true
    };
  },
  created() {
    window.addEventListener('orientationchange', this.handleOrientationChange);
  },
  unmounted() {
    window.removeEventListener('orientationchange', this.handleOrientationChange);
  },
  methods: {
    // Handle orientation change
    handleOrientationChange() {
      // Determine the current orientation of the device
      this.isPortrait = (window.orientation === 0 || window.orientation === 180);
      // Adapt UI components, perform any required actions
      console.log('Orientation is now ' + (this.isPortrait ? 'portrait' : 'landscape'));
    }
  }
});
Defines a Vue component that automatically listens for orientation changes and updates its data accordingly. The 'isPortrait' data property is used to determine the orientation and adapt the UI components.