主题
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.
示例
用法
🌐 Usage
ts
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 a hydration mismatch
ts
import { 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