Skip to content

useMediaQuery ​

Category
Export Size
455 B
Last Changed
5 minutes ago

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

Demo ​

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

Type Declarations ​

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>

Source ​

Source • Demo • Docs

Contributors ​

jojo

Changelog ​

No recent changes

Released under the MIT License.