cnpm install enquire.js --save或 cnpm install enquire.js --save

创建device.js

import enquireJs from 'enquire.js'

export const DEVICE_TYPE = {
  DESKTOP: 'desktop',
  TABLET: 'tablet',
  MOBILE: 'mobile'
}

export const deviceEnquire = function (callback) {
  const matchDesktop = {
    match: () => {
      callback && callback(DEVICE_TYPE.DESKTOP)
    }
  }

  const matchLablet = {
    match: () => {
      callback && callback(DEVICE_TYPE.TABLET)
    }
  }

  const matchMobile = {
    match: () => {
      callback && callback(DEVICE_TYPE.MOBILE)
    }
  }

  // screen and (max-width: 1087.99px)
  enquireJs
    .register('screen and (max-width: 576px)', matchMobile)
    .register('screen and (min-width: 576px) and (max-width: 1199px)', matchLablet)
    .register('screen and (min-width: 1200px)', matchDesktop)
}

vue使用

import { deviceEnquire, DEVICE_TYPE } from '@/utils/device'
	export default {
		mounted () {
			deviceEnquire(deviceType => {
			  switch (deviceType) {
			    case DEVICE_TYPE.DESKTOP:
			      console.log(DEVICE_TYPE.DESKTOP)
			      break
			    case DEVICE_TYPE.TABLET:
			      console.log(DEVICE_TYPE.TABLET)
			      break
			    case DEVICE_TYPE.MOBILE:
			    default:
			      console.log(DEVICE_TYPE.MOBILE)
			      break
			  }
			})
		}
	}
Logo

前往低代码交流专区

更多推荐