refactor: per-request mobile detection

This commit is contained in:
Tim
2025-08-08 18:12:40 +08:00
parent 25a64d7666
commit 27a2591904
7 changed files with 47 additions and 41 deletions

View File

@@ -1,45 +1,46 @@
import { ref, computed } from 'vue'
import { ref, computed, onUnmounted } from 'vue'
import { useRequestHeaders } from 'nuxt/app'
const width = ref(0)
const isClient = ref(false)
export const useIsMobile = () => {
const width = ref(0)
const isClient = ref(false)
// 检测移动设备的用户代理字符串
const isMobileUserAgent = () => {
let userAgent = ''
const isMobileUserAgent = () => {
let userAgent = ''
if (typeof navigator !== 'undefined') {
userAgent = navigator.userAgent.toLowerCase()
} else {
// 服务端:从请求头获取用户代理字符串
const headers = useRequestHeaders(['user-agent'])
userAgent = (headers['user-agent'] || '').toLowerCase()
if (typeof navigator !== 'undefined') {
userAgent = navigator.userAgent.toLowerCase()
} else {
const headers = useRequestHeaders(['user-agent'])
userAgent = (headers['user-agent'] || '').toLowerCase()
}
const mobileKeywords = [
'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'windows phone',
'mobile', 'tablet', 'opera mini', 'iemobile'
]
return mobileKeywords.some(keyword => userAgent.includes(keyword))
}
const mobileKeywords = [
'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'windows phone',
'mobile', 'tablet', 'opera mini', 'iemobile'
]
if (typeof window !== 'undefined') {
isClient.value = true
const updateWidth = () => {
width.value = window.innerWidth
}
updateWidth()
window.addEventListener('resize', updateWidth)
onUnmounted(() => {
window.removeEventListener('resize', updateWidth)
})
}
return mobileKeywords.some(keyword => userAgent.includes(keyword))
}
return computed(() => {
if (isClient.value) {
return width.value > 0 ? width.value <= 768 : isMobileUserAgent()
}
// 客户端初始化
if (typeof window !== 'undefined') {
isClient.value = true
width.value = window.innerWidth
window.addEventListener('resize', () => {
width.value = window.innerWidth
return isMobileUserAgent()
})
}
// 服务端和客户端的移动设备检测
export const isMobile = computed(() => {
if (isClient.value) {
// 客户端:优先使用窗口宽度,如果窗口宽度不可用则使用用户代理
return width.value > 0 ? width.value <= 768 : isMobileUserAgent()
}
// 服务端:使用请求头中的用户代理字符串
return isMobileUserAgent()
})