响应式判断双端

412 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

前言

在学习中遇到了一个项目同时兼容PC和移动端的需求,在PC或移动端需要使用不同的路由,所以需要判断当前的环境是PC还是移动端。

常规方法

我们可以在utils中定义一个方法,用来判断当前是否在移动端.使用计算属性会更加灵活

/utils/flexible.js

import { computed } from 'vue'

export const isMobileTerminal = computed(() => {
 
})

为了简单的举个栗子,判断是否为移动端的逻辑,我们判断当前的屏幕宽度是否小于一个值,如果小于这个值,说明当前环境为移动端

constants/index.js中定义常量

export const PC_DEVICE_WIDTH = 1280

更新isMobileTerminal中的逻辑

import { computed } from 'vue'
import { PC_DEVICE_WIDTH } from '@/constants/index'

export const isMobileTerminal = computed(() => {
  return document.documentElement.clientWidth < PC_DEVICE_WIDTH
})

接下来我们将其返回值显示出来

App.vue

<template>
  <div>
    {{ isMobileTerminal }}
  </div>
</template>

<script setup>
import { isMobileTerminal } from '@/utils/flexible'
</script>

<style lang="scss" scoped></style>

1.png

可以看到始终显示为falseisMobileTerminal方法中全部为固定的值,那么如何解决响应式的问题

vueuse

vueuse中有许多方法,我们需要用到useWindowSize

2.png

安装vueuse

npm i @vueuse/core@8.1.2

flexible.js中导入useWindowSize

import { useWindowSize } from '@vueuse/core'

因为我们的逻辑是用当前屏幕的宽度去判断是否为移动端,所以解构出width

const { width } = useWindowSize()

打印出width的值

3.png

可以看到width为响应式的值,判断是需要使用.value,,使用width.value替换document.documentElement.clientWidth

import { computed } from 'vue'
import { PC_DEVICE_WIDTH } from '@/constants/index'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()

export const isMobileTerminal = computed(() => {
  console.log(width)
  return width.value < PC_DEVICE_WIDTH
  // return document.documentElement.clientWidth < PC_DEVICE_WIDTH
})

再去首页中可以看到当屏幕宽度缩小到一定范围后,方法返回true

4.png

这样就能响应式判断当前的设备环境