enquire.js 轻量级css响应查询JavaScript库

1,334 阅读1分钟

相信各位小伙伴在工作中不免会遇到需要做移动端适配的功能,目前比较流行的是viewport和rem适配方案,但是偶尔也会遇到一些不一样的需求,比如我们需要在vue或者js中使用媒体查询,这时候enquire.js便派上了用场。

介绍

enquire.js 是一个轻量级的纯JavaScript库,用于响应css媒体查询,可以在JavaScript中使用媒体查询时,更加方便以及更加具有灵活性。本文向大家介绍了如何在vue项目中使用enquire.js

安装

// 使用npm
npm install enquire.js
// 使用yarn
yarn add enquire.js

使用

  • 创建enquire.ts
import { EnumDeviceType } from '@/enum/system';
import { useAppStore } from '@/store/modules';
import enquireJs from 'enquire.js';
import { onMounted } from 'vue';

export const AppDeviceEnquire = () => {
  onMounted(() => {
    const app = useAppStore();
    deviceEnquire((deviceType: EnumDeviceType) => {
      switch (deviceType) {
        case EnumDeviceType.desktop:
          app.setDeviceType(EnumDeviceType.desktop);
          break;
        case EnumDeviceType.tablet:
          app.setDeviceType(EnumDeviceType.tablet);
          break;
        case EnumDeviceType.mobile:
          app.setDeviceType(EnumDeviceType.mobile);
          break;
        default:
          app.setDeviceType(EnumDeviceType.desktop);
          break;
      }
    });
  });
};

/**
 * 响应式检测
 * @param {*} callback
 */
export const deviceEnquire = function (callback) {
  const matchDesktop = {
    match: () => {
      callback && callback(EnumDeviceType.desktop);
    },
  };

  const matchLablet = {
    match: () => {
      callback && callback(EnumDeviceType.tablet);
    },
  };

  const matchMobile = {
    match: () => {
      callback && callback(EnumDeviceType.mobile);
    },
  };

  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);
};

  • 在App.vue中引入
<script setup lang="ts">
import { AppDeviceEnquire } from '@/core';
AppDeviceEnquire();
</script>
  • 结合pinia

关于Pinia大家可以移步我的另一篇文章——《Pinia.js入门指南》

import { EnumDeviceType } from '@/enum/system';
import { nextTick } from 'vue';
import { defineStore } from 'pinia';

interface AppState {
  /** 设备终端信息(移动端适配) */
  device: EnumDeviceType;
}

export const useAppStore = defineStore('app-store', {
  state: (): AppState => ({
    device: EnumDeviceType.desktop,
  }),
  actions: {
    async setDeviceType(deviceType: EnumDeviceType) {
      this.device = deviceType;
    }
  },
});

  • 在页面中使用
const app = useAppStore();
// 获取设备终端判断
const isMobile = computed(() => {
  return app.device === EnumDeviceType.mobile;
});

总结

enquire.js相对于需要在js中做媒体查询而言还是十分方便的,也可以结合vuex或者pinia去将设备类型存储,然后运用到实际页面中判断。