Skip to content

useMediaQuery

反应式 媒体查询。创建 MediaQueryList 对象后,你可以检查查询结果或在结果更改时接收通知。

¥Reactive Media Query. Once you've created a MediaQueryList object, you can check the result of the query or receive notifications when the result changes.

示例

isLargeScreen: false
prefersDark: false

用法

¥Usage

js
import { useMediaQuery } from '@vueuse/core'

const isLargeScreen = useMediaQuery('(min-width: 1024px)')
const isPreferredDark = useMediaQuery('(prefers-color-scheme: dark)')

服务器端渲染和 Nuxt

¥Server Side Rendering and Nuxt

如果你在启用 SSR 的情况下使用 useMediaQuery 则需要指定要在服务器上渲染的屏幕尺寸,并在水化之前指定以避免水化不匹配

¥If you are using useMediaQuery with SSR enabled, then you need to specify which screen size you would like to render on the server and before hydration to avoid an hydration mismatch

js
import { breakpointsTailwind, useMediaQuery } from '@vueuse/core'

const isLarge = useMediaQuery(
  '(min-width: 1024px)',
  { ssrWidth: 768 } // Will enable SSR mode and render like if the screen was 768px wide
)

console.log(isLarge.value) // always false because ssrWidth of 768px is smaller than 1024px
onMounted(() => {
  console.log(isLarge.value) // false if screen is smaller than 1024px, true if larger than 1024px
})

或者,你可以使用 provideSSRWidth 为你的应用全局设置此功能

¥Alternatively you can set this up globally for your app using provideSSRWidth

类型声明

typescript
/**
 * Reactive Media Query.
 *
 * @see https://vueuse.org/useMediaQuery
 * @param query
 * @param options
 */
export declare function useMediaQuery(
  query: MaybeRefOrGetter<string>,
  options?: ConfigurableWindow & {
    ssrWidth?: number
  },
): ComputedRef<boolean>

源代码

源代码示例文档

变更日志

v12.3.0 on 1/2/2025
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
v12.1.0 on 12/22/2024
55965 - feat(useSSRWidth): add optional support for SSR in useMediaQuery and useBreakpoints (#4317)
3af75 - fix: the return value should be computed (#4403)

VueUse 中文网 - 粤ICP备13048890号