主题
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>