Skip to content

useMediaQuery

类别
导出体积
455 B
上次更改
5 minutes ago

响应式的媒体查询。一旦你创建了一个 MediaQueryList 对象,你可以检查查询结果或在结果变化时接收通知。

示例

isLargeScreen: false
prefersDark: false

使用方法

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

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

Server Side Rendering and Nuxt

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

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

类型声明

typescript
/**
 * 响应式媒体查询。
 *
 * @see https://vueuse.org/useMediaQuery
 * @param query
 * @param options
 */
export declare function useMediaQuery(
  query: MaybeRefOrGetter<string>,
  options?: ConfigurableWindow & {
    ssrWidth?: number
  },
): ComputedRef<boolean>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Antério Vieira
Anthony Fu
Fernando Fernández
Adrien Foulon
Alex
Indrek Ardel
Zhousg
Young
Jelf
Dominik Freier
webfansplz
Eureka
karma
Alex Kozack
Jacob Clevenger

更新日志

Pending for release...
c6c6e - feat: use useEventListener where it was not being used (#4479)
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)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.3.0 on 7/30/2023
f3969 - fix: only add/remove event listeners on query change (#3236)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v10.0.0-beta.3 on 4/12/2023
4e7b0 - fix(useWindowSize)!: use media query instead of orientationchange listener (#2919)